The Clean Array#Map Method
So, there is at least one way to solve my problem with Ruby.
The problem is that I have a bunch of hex color codes and I want to append the number sign before each one. Well, I say a bunch… But, I’ll only use 5. So here is our slick array:
colors = ["000000", "000033", "000066", "000099", "0000CC"]
Now, here is one way that I could solve this problem:
This puts the newly formed elements inside of the new_colors array.
This, however, is not the cleanest way to solve the problem.
new_colors = Array.new
colors = ["000000", "000033", "000066", "000099", "0000CC"]
colors.each do |color|
new_colors << "\##{color}"
end
puts new_colors #=> ["#000000", "#000033", "#000066", "#000099", "#0000CC"]
We can look deep inside the Array class for a method called “Map” AKA “Collect”.
/*
* call-seq:
* array.collect! {|item| block } -> array
* array.map! {|item| block } -> array
*
* Invokes the block once for each element of _self_, replacing the
* element with the value returned by _block_.
* See alsoEnumerable#collect.
*
* a = [ "a", "b", "c", "d" ]
* a.collect! {|x| x + “!” }
* a #=> [ "a!", "b!", "c!", "d!" ]
*/
Using this same method, we can do what we want in just ONE line.
colors = ["000000", "000033", "000066", "000099", "0000CC"]
colors.map! {|color| ‘#’+color} #=> ["#000000", "#000033", "#000066", "#000099", "#0000CC"]
This may seem trivial with a small number of hex codes, but when you have around, say, 216. This can be a great solution.
Do you have any good ideas to make this script better?
Add a little comment!
Post a Comment