Make Ruby loop return “x” images rather than x, the integer
Question
The following returns whatever integer I feed it as a parameter.
def space(spacer_count)
spacer_count.times do
image_tag("24gray/spacer.png", :class => "spacer")
end
end
How do I make it return the desired number of images? E.g., I want space(6) to return six copies of spacer.png, not the number "6".
Thanks!
Solution
If you want to return a single string containing all the <img>
tags, then you can do the following:
def space(spacer_count)
image_tag("24gray/spacer.png", :class => "spacer") * spacer_count
end
OTHER TIPS
If you use Ruby 1.8.7 or greater
def space(spacer_count)
spacer_count.times.map do
image_tag("24gray/spacer.png", :class => "spacer")
end
end
With Ruby 1.8.6 you should use a workaround (it also works with 1.8.7 and greater). First workaround.
def space(spacer_count)
Array.new(spacer_count).map do
image_tag("24gray/spacer.png", :class => "spacer")
end
end
Second workaround (using ranges).
def space(spacer_count)
(1..spacer_count).map do
image_tag("24gray/spacer.png", :class => "spacer")
end
end
There are some good answers here already, so I'm not going to give another one. However, it might help to understand what's going wrong here. Every block in Ruby returns the evaluation of it's last statement.
The times method returns the number of times the blocks was run. The each method returns the array that the block was run on.
Seeing a pattern here? Most of these iterator methods return what was passed to it.
Blocks are passed to the calling function almost like an argument. Essentially this is what's happening in your code.
block = Proc.new { image_tag("24gray/spacer.png", :class => "spacer")}
def space(spacer_count)
spacer_count.times(&block)
end
Knowing now that iterators return what was passed to it, you can see why space(6) returns 6