【发布时间】:2016-01-01 22:31:01
【问题描述】:
在下面的 ruby 代码中:
require 'sinatra'
class Stream
def each
100.times { |i| yield "#{i}\n" }
end
end
get ('/') {Stream.new}
get '/' do
Stream.new
end
第 9 行的代码和第 10-12 行的代码在功能上是等价的。
第 9 行的代码看起来没问题。它必须是一个体面的函数,参数 '/' 在括号内,代码在花括号内。
但是在第 10-12 行中,参数“/”没有括号。还是函数吗?如果它是函数,为什么它的参数不包含括号?
当我浏览 ~/.rbenv/versions/custom-2.0.0-p247/lib/ruby/gems/2.0.0/gems/sinatra-1.4.4/lib/sinatra/base.rb 这个“ get" 已定义,我发现:
# Defining a `GET` handler also automatically defines
# a `HEAD` handler.
def get(path, opts = {}, &block)
conditions = @conditions.dup
route('GET', path, opts, &block)
@conditions = conditions
route('HEAD', path, opts, &block)
end
看起来“get”被定义为可选的 {} 或 &block,为什么会这样?
当某些东西被定义为一个块时,Ruby 是否要求在参数周围不要有任何括号?
【问题讨论】:
-
一个基本的 Ruby 教程可能会回答你的问题。
-
感谢您的评论,但我已经有一本(印刷的)Ruby 书,很难找到关于这个特定主题的信息 :)
-
该特定主题的信息在所有 Ruby 教程中都是相同的,因为它们讨论了方法、向它们传递参数以及使用带有方法的块。 Sinatra 没有做任何不同的事情,它使用 Ruby 的基本构建块。
-
如果其中任何一个回答了您的问题,请将其标记为答案。