,我要在这件事上大做文章。这就是我所有的一切。帮助所有强大的众神!
ages = [23, 101, 7, 104, 11, 94, 100, 121, 101, 70, 44]
under_100 = Proc.new { |x| x < 100 }发布于 2014-01-22 08:53:14
如下所示
ages = [23, 101, 7, 104, 11, 94, 100, 121, 101, 70, 44]
under_100 = Proc.new { |x| x < 100 }
ages.select(&under_100) # => [23, 7, 11, 94, 70, 44]
ages.select { |x| x < 100 } # I would do this way or
ages.select(&100.method(:>)) # this way.100.method(:>)创建了Method对象(选中此Object#method),与您作为Proc.new { |x| x < 100 }创建的对象相同。现在,将&应用于这个proc/method对象,用#select方法将其转换为一个块。
发布于 2014-01-22 09:09:57
ages = [23, 101, 7, 104, 11, 94, 100, 121, 101, 70, 44]
under_100 = Proc.new { |x| x < 100 }
p under_100.call(201) #=> false
p under_100.call(23) #=> trueMap对每个元素运行proc并返回结果:
p ages.map(&under_100) #=> [true, false, true, false, true, true, false, false, false, true, true]Select遍历所有元素,只返回计算结果为true的元素:
p ages.select(&under_100) #=> [23, 7, 11, 94, 70, 44]它也可以写成这样:
result = []
ages.each{|age| result.push(age) if under_100.call(age)}
p result #=> [23, 7, 11, 94, 70, 44]这就是为什么在使用数组的if方法时不需要使用任何select。
发布于 2014-01-22 09:16:31
如果没有proc,我们可以将其作为
ages = [23, 101, 7, 104, 11, 94, 100, 121, 101, 70, 44]
ages.each do |x|
if x < 100;
puts "#{x} is less than 100";
end
end https://stackoverflow.com/questions/21278161
复制相似问题