ruby1.9中的Proc#===,Proc#curry

Tuesday, July 20, 2010

在Ruby 1.9中Proc#===是Proc#call的一个别名,意味这Proc对象可以使用在case语句中

def multiple_of(factor)
  Proc.new{|product| product.modulo(factor).zero?}
end
case number
  when multiple_of(3): puts "Multiple of 3"
  when multiple_of(7): puts "Multuple of 7"
end

it_is_day_of_week = lambda{ |day_of_week, date| date.wday == day_of_week }
it_is_saturday = it_is_day_of_week.curry[6]
it_is_sunday = it_is_day_of_week.curry[0]
case Time.now
when it_is_saturday
  puts "Saturday!"
when it_is_sunday
  puts "Sunday!"
else
  puts "Not the weekend"
end

This entry was tagged hidden-features, Ruby and tips

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top