这个Ruby语法是什么?

时间:2013-10-15 08:28:36

标签: ruby

我刚刚阅读了以下代码:

class Dir
   def self.create_uniq &b  ### Here, & should mean b is a block
      u = 0
      loop do
      begin
         fn = b[u]   ### But, what does b[u] mean? And b is not called.
         FileUtils.mkdir fn
         return fn
      rescue Errno::EEXIST
         u += 1
      end
    end
    io
  end
end

我把我的困惑作为评论写在代码中。

2 个答案:

答案 0 :(得分:12)

在最后使用&b定义方法允许您使用作为Proc对象传递给方法的块。

现在,如果你有Proc个实例,[]语法是call的简写:

p = Proc.new { |u| puts u }
p['some string']
# some string
# => nil

此处记录 - > Proc#[]

答案 1 :(得分:1)

& prefix运算符允许一个方法将传递的块捕获为命名参数。 e.g:

def wrap &b
  3.times(&b)
  print "\n"
end

现在,如果您调用上述方法:

wrap { print "Hi " }

然后输出将是:

Hi Hi Hi
相关问题