Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 无变量块_Ruby_Variables_Block - Fatal编程技术网

Ruby 无变量块

Ruby 无变量块,ruby,variables,block,Ruby,Variables,Block,我面临着一个我不太理解的语法。代码如下: config.middleware.insert_before 0, "Rack::Cors",:logger => (-> { Rails.logger }) do allow do origins '*' resource '/cors', :headers => :any, :methods => [:post],

我面临着一个我不太理解的语法。代码如下:

   config.middleware.insert_before 0, "Rack::Cors",:logger => (-> { Rails.logger }) do
      allow do
        origins '*'

        resource '/cors',
          :headers => :any,
          :methods => [:post],
          :credentials => true,
          :max_age => 0

        resource '*',
          :headers => :any,
          :methods => [:get, :post, :delete, :put, :options, :head],
          :max_age => 0
      end
    end
在第一行的
do
之后,没有像在常规块中那样声明变量,例如:

array.each do |element| 
  puts element
end
array = [1, 2, 3]
array.each do
  puts "Hello"
end
# => Hello
# Hello
# Hello

我应该如何解释第一个示例?

它是一个不接受块变量的块,或者是一个可以传递块变量但不使用块变量的块。

不强制将块变量传递给块:

▶ def helloer &cb
▷   puts cb.call
▷ end  
# => :helloer
▶ helloer { 'Hello, world' }
Hello, world
# => nil

块不必有变量。请查看以下内容,例如:

array.each do |element| 
  puts element
end
array = [1, 2, 3]
array.each do
  puts "Hello"
end
# => Hello
# Hello
# Hello

在定义块时,如果您不确定使用的值将是什么,则块变量非常有用。但是,如果您已经可以访问这些值,则可以直接使用它们,而不是依赖传递给块的变量

让我提供一些非常基本的例子:

# run the following code

class CB
  def self.show_num
    yield
  end
end

CB.show_num do
  1
end
如果您不知道将使用什么值,您可以使块灵活,即让它预期参数

# run the following code

class CB
  CONSTA = 1
  CONSTB = 2

  def self.show_with_sign
    val = yield(CONSTA, CONSTB).round(2)
    "#{val}%"
  end
end

CB.show_with_sign do |num, den|
  100 * num.fdiv(den)
end

在您共享的代码中,声明块的位置已经存在所有信息。简单地说,您已经有了生成块输出的值。因此,它按原样传递给方法,没有任何参数。

为什么会得到
:将
配置为定义
helloer
的返回值?我的意思是,您的预期输出所依赖的信息/值/变量没有任何缺失。这是一个非常令人困惑的解释。块参数从来不是“必需的”。它们始终是可选的,您是否应该包含它们完全取决于方法实现和您的用例。答案使用示例展示了块参数不总是必要的方式和原因,从而澄清了OP的困惑,这可能是它被接受的原因。但是我已经将单词“required”编辑为“有用”以避免任何混淆。给定的代码示例很可能使用BasicObject#instance_exec或#instance_eval来更改传递给方法的块中self的含义。这种技术通常用于制作DSL。@iron_davior,你是说config.middleware.insert_在使用方法定义中提到的东西之前?