-
-
Save dkubb/1130086 to your computer and use it in GitHub Desktop.
case with predicates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'backports' # aliases Proc#=== to Proc#call | |
rs = (0..10000).to_a.sample(30) | |
rs.each do |r| | |
case r | |
when lambda { |n| n.zero? } then puts "#{r} is zero" | |
when lambda { |n| (n % 5).zero? } then puts "#{r} is fiven" | |
when lambda { |n| (n % 4).zero? } then puts "#{r} is fourven" | |
when lambda { |n| (n % 3).zero? } then puts "#{r} is threeven" | |
when lambda { |n| n.even? } then puts "#{r} is even" | |
when lambda { |n| n.odd? } then puts "#{r} is odd" | |
else | |
raise 'unpossible' | |
end | |
end |
I'd still very much like to have &:method work in when arg lists. I spent some time trying to hack parse.y over the weekend, actually, to see if I could make it work in some frankenstein-like manner, but my version of bison seemed not to be playing nicely. :(
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@dkubb—
I agree that this opens terrific options for new types of idiomatic Ruby. I would love to see more examples of how people are using this for great justice, but I suspect such examples will be ill-suited to explication in gist form, by virtue of the substance of my complaint.
To be clear, my point is that this specific example should not be emulated. If the predicates are statically defined in the same scope as a
case
statement, do the simple thing: use thecase
statement as Matz intended :P...pardon me while I continue turning into a cantankerous old grump...