在下面的 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,为什么会这样?
当某些东西被定义为 block 时,Ruby 是否要求参数周围没有任何括号?
最佳答案
正如 Simone 所指出的,圆括号在 ruby 中是可选的,因此您的 get
方法可以在有或没有圆括号的情况下被调用。
It looks like "get" is defined optionally as {} or &block, why is that so?
get
函数接受三个参数。第一个参数是 path
,第二个是 Hash默认值为空,第三个是 block 。
ruby 中的 block 可以写成 {}
或 do...end
。因此,在您的两个示例中,您都将一个 block 传递给 get
函数
关于ruby - Sinatra (Ruby) 中 get 方法的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21387066/