Can procs be used with case statements in Ruby 2.0? -


i remember procs being allowed in case statements in ruby 2.0, can't google it.

i tried checking ruby 2.0.0 news , how write switch statement in ruby. visited http://ruby-doc.org , link had keywords ruby 1.9, not ruby 2.0.

are procs allowed in case statements?

yes.

2.0.0p0 :001> lamb = ->(x){ x%2==1 } #=> #<proc:0x007fdd6a97dd90@(irb):1 (lambda)>   2.0.0p0 :002> case 3; when lamb p(:yay); end :yay #=> :yay   2.0.0p0 :003> lamb === 3 #=> true   2.0.0p0 :007> lamb === 2 #=> false  

however, no different 1.9.1 since proc#=== defined then. since ruby-docs seems have problem showing method, clear documentation says proc === obj:

invokes block obj proc's parameter #call. allow proc object target of when clause in case statement.


for ruby beginner, when clause in ruby's case statements takes value in clause , calls === method on it, passing in argument case statement. so, example, code…

case "cats"   when /^cat/ puts("line starts cat!")   when /^dog/ puts("line starts dog!") end 

…runs /^cat/ === "cats" decide if it's match; regexp class defines === method perform regex matching. thus, can use own object in when clause long define === it.

moddable = struct.new(:n)   def ===(numeric)     numeric % n == 0   end end  mod4 = moddable.new(4) mod3 = moddable.new(3)  12.times |i|   case     when mod4       puts "#{i} multiple of 4!"     when mod3       puts "#{i} multiple of 3!"   end end  #=> 0 multiple of 4! #=> 3 multiple of 3! #=> 4 multiple of 4! #=> 6 multiple of 3! #=> 8 multiple of 4! #=> 9 multiple of 3! 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -