D
Diego Virasoro
Hi all,
I just wanted to share a couple of things I've found out lately. I
imagine they are well known to the experts here, but I thought maybe
there are other newbies out there that could benefit from it too.
1) Using proc in the case statement:
I find the case statement particularly elegant: especially when
there's a long list of choices I much prefer it to using if...
elsif... else... end. That said the latter offers a lot more
flexibility. Still a lot can be accomplished by using procs. For
example:
case val
when Hash
....
when lambda{|x| x.respond_to?
to_ary) && x.length>1}
....
end
The block takes the case argument and its output (generally true or
false...) is used to decide if the branch should be run or not.
2) Passing a block to map or similar methods.
Say you have an array of numbers, and you want to invoke #abs for each
number. Rather than:
x = [1,-2,3,-4,5]
x.map{|x| x.abs}
you can use:
x = [1,-2,3,-4,5]
x.map(&:abs)
It may not seem much in this instance, but I found it a lot cleaner in
some cases, especially when there is a long chain of methods.
Hope that helped _someone_
Diego
I just wanted to share a couple of things I've found out lately. I
imagine they are well known to the experts here, but I thought maybe
there are other newbies out there that could benefit from it too.
1) Using proc in the case statement:
I find the case statement particularly elegant: especially when
there's a long list of choices I much prefer it to using if...
elsif... else... end. That said the latter offers a lot more
flexibility. Still a lot can be accomplished by using procs. For
example:
case val
when Hash
....
when lambda{|x| x.respond_to?
....
end
The block takes the case argument and its output (generally true or
false...) is used to decide if the branch should be run or not.
2) Passing a block to map or similar methods.
Say you have an array of numbers, and you want to invoke #abs for each
number. Rather than:
x = [1,-2,3,-4,5]
x.map{|x| x.abs}
you can use:
x = [1,-2,3,-4,5]
x.map(&:abs)
It may not seem much in this instance, but I found it a lot cleaner in
some cases, especially when there is a long chain of methods.
Hope that helped _someone_
Diego