ruby传递&:键作为映射而不是块的参数

时间:2017-05-16 13:41:55

标签: ruby rubocop

我写了以下代码:

def report_view_classes
  [
    Hourdiff,
    AverageTimeForFirstReferrals,
    CountZipCodeByUserids,
    FirstRentForUsers,
  ]
end

def load_views
  report_view_classes.each do |report_view_class|
    report_view_class.create
  end

但是rubocop给了我以下警告:

C: Pass &:create as an argument to each instead of a block.
  report_view_classes.each do |report_view_class

我很困惑该怎么做

1 个答案:

答案 0 :(得分:0)

Ruby有一个简单块的简写。

["apple", "pear", "grape"].map { |fruit| fruit.upcase }

# This does the same thing with less code:

["apple", "pear", "grape"].map(&:upcase)