Proc#=== + Symbol#to_proc = A Near Miss

Here’s a an application of combining my Proc#=== suggestions and Rails’ Symbol#to_proc, both now part of the core library in Ruby 1.9, that I thought of this morning.

1 case number
2 when :even?.to_proc
3   puts "Even!"
4 when :odd?.to_proc
5   puts "Odd!"
6 when :zero?.to_proc
7   puts "Zero!"
8 end

which is equivalent to writing

1 if number.even?
2   puts "Even!"
3 elsif number.odd?
4   puts "Odd!"
5 elsif number.zero?
6   puts "Zero!"
7 end

Although I will admit the if/elsif example is more readable, mainly because of the presence of all those (unecessary) to_procs. Ideally I would liked to have been able to write the when clauses like

1 when :even?
2   puts "Even!"

and so on without those to_procs all over the place.

I initially thought about defining Symbol#=== as

1 class Symbol
2   def ===( *values )
3     self.to_proc.call( *values )
4   end
5 end

but it has implications if we’re using === to compare two Symbols, as there is no way to differentiate if we want to merely compare them using == (as the behaviour is now and which is perfectly logical and correct) or if we want to use the new Symbol#=== functionality defined above. So I’ll admit this is a near miss in terms of Ruby dynamic language coolness.


Farrel Lifson is a lead developer at Aimred.

About Aimred

Aimred is a specialist Ruby and Ruby on Rails development house and consultancy based in Cape Town, South Africa.

We provide Ruby and Ruby on Rails development, consulting and training services to businesses and organisations of all sizes. If you want to find out how we can help you, contact us at info@aimred.com.

Recent Posts

Yearly Archives