def some_method(foo)
results = []
foo.each {|f| results << f.reverse}
return results
end
As you can see, that is some pretty ugly code, but it's also a common
scenario. How can I make it a little less ugly?
Thanks,
Michael Boutros
--
Posted via http://www.ruby-forum.com/.
Map:
def some_method(foo)
foo.map {|f| f.reverse}
end
or inject, but it's less clear in this case:
def some_method(foo)
foo.inject([]) {|arr, f| arr << f.reverse}
end
In this specific case...
def some_method(foo)
foo.map { |f| f.reverse }
end
Use methods which return new objects and take advantage of implicit
return values.
-Justin
If I understand your goal, that's what map is for:
foo.map {|f| f.reverse}
"map" can also be spelled "collect".
-A
foo.each { |word| word.reverse! }
should do the trick.
--
Andrei Maxim
http://andreimaxim.ro
def some_method foo
foo.map {|f| f.reverse}
end
Thanks for that, I'll be using that more often now :) However, I'm
having trouble refactoring this code into something like yours...
def get_text(*elements)
results = []
elements.each {|element| results << self.search(element).first}
return results
def get_text( *elements )
elements.map{ |el| search( element ).first }
end
def get_text(*elements)
elements.map{|element| self.search(element).first}
end
def get_text(*elements)
elements.map {|elem| self.search(elem).first }
end
This should do what you want.
Greetings,
Sascha
- Michael Boutros
> Thanks so much for all the replies :) So, what I've gathered is that
> map
> basically loops through all the values of an array, does whatever the
> block says to do, and then places it back into the array. Correct?
>
> - Michael Boutros
map creates a new array
If you really want to modify the array in place, you can use map!
instead.
-Rob
Rob Biedenharn http://agileconsultingllc.com
R...@AgileConsultingLLC.com
If I understand your sentence correctly -- no, that's incorrect.
My understanding is that you expect #map or #collect to do this:
foo = %w(rgb irs rib)
foo.map {|f| f.gsub('r', 'e')}
puts foo
> egb
> ies
> eib
What it actually does is this:
foo = %w(rgb irs rib)
bar = foo.map {|f| f.gsub('r', 'e')}
puts foo
> rgb
> irs
> rib
puts bar
> egb
> ies
> eib
Thus, the proposed method declaration:
def some_method(foo)
foo.map { |f| f.reverse }
end
. . would return the reversed list, exactly the same as a version with
an explicit return statement. It does not alter the provided variable at
all, but instead outputs a brand-new list object.
--
CCD CopyWrite Chad Perrin [ http://ccd.apotheon.org ]
They always say that when life gives you lemons you should make lemonade.
I always wonder -- isn't the lemonade going to suck if life doesn't give
you any sugar?