30 Days of Tech: Day 22 - Class#to_proc
June 22nd, 2008
Here’s a little hack for Ruby classes that comes from a project.
class Class
def to_proc
method(:new).to_proc
end
end
If you’ve ever used map (a.k.a. collect) to create a bunch of objects you might be familiar with code that looks something like this.
value_list.map {|v| Something.new(v)}
With Class#to_proc this can be simplified to
value_list.map(&Something)
This works very well for map, but I haven’t seen Class#to_proc become useful in any other situation to date. Even changing map to collect changes my opinion of it’s expressiveness. I don’t know that Class#to_proc is pulls its weight in our situation, but I just like the map statement above too much to give it up.
Sorry, comments are closed for this article.