tags:

views:

93

answers:

3

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!

+2  A: 

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
Simone Carletti
+4  A: 

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
Phil Ross
Nice one! I have never considered the idea of using * in this case.
Simone Carletti
Cheers. Worked a charm. :-)
steven_noble
+2  A: 

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

EmFi
Thanks for the explanation.
steven_noble
No problem. I believe that understanding the root cause goes a lot farther in preventing the issue than just knowing a work around.
EmFi