On Apr 30, 12:26 am, “[email protected]” [email protected] wrote:
I am not clear on the advantage of returning proc object vs just the
result as an array. TIA.
Hi Bala,
From the short example you provide, there really is no advantage to
returning a Proc. However, if you needed to perform the same
filtering operation in more than one place in your code, there might
be an advantage to re-using the same filter, so that code does not
have to be repeated.
Or alternatively, say you had an application that offered its users
the ability to apply many commonly used filters (perhaps via a drop-
down menu). Each of these filters might have an associated name, use
example, and the Proc used to implement it. Well, name, example, and
Proc could be members of a hash or alternatively instance variables in
an instance of some Filter class.
As Benjohn pointed out, it’s a matter of abstraction. That Ruby
allows one to store Procs in variables, have methods take Procs as
parameters or return a Proc means Ruby has “first class functions”.
You can read more about the concept here:
http://en.wikipedia.org/wiki/First-class_function
I suspect the code you showed us is someone’s attempt to demonstrate
the power of Procs and first class functions. That kind of filtering
would more commonly be done with Enumerable#select or
Enumerable#reject. Since Arrays are Enumerable, the code would
become:
list_2 = list_1.select { |item| item.ordinal =~ /th$/ }
(Also note that because the result of the =~ operator can be evaluated
as true or false, the trinary conditional operator ?: is unnecessary.)
Eric
Are you looking for on-site Ruby or Ruby on Rails training
that’s been highly reviewed by former students?
http://LearnRuby.com