Unless you explicitly say "return ", the last evaluated line
in your method will be used as the return value. You can see this by
using irb:
irb(main):002:0> hsh = { 1 => 2, 3 => 4, 5 => 6 }
=> {5=>6, 1=>2, 3=>4}
irb(main):005:0> hsh.keys.each { |key| key.to_s }
=> [5, 1, 3]
As you can see, even though we do something to each key, the result of
to_s is simply being discarded at the end of each loop. And since you
never actually specifically “return” anything, the last evaluated value
is being used. The last thing that was evaluated was “hsh.keys” (or in
your case, “menu.keys”), so that’s being returned.
The most Ruby-like way of fixing your problem would be to use a
continuation using “yield”:
def menu(menu)
menu.keys.each { |key|
if !menu[key][‘action’].nil? then
yield content_tag( :li, link_to( key, menu[key][‘action’] ) )
end
}
end
You would call this method in your view with a block, for instance:
<% menu(menu) do |tag| %>
<%= tag %>
<% end %>
There’s probably some bugs in there, since I didn’t actually check it
using ERb, but the general idea is solid.
Tim M.
Andy W. wrote:
Hi,
I have the following code in a helper.
def menu( menu )
menu.keys.each{|key|
if !menu[key][‘action’].nil? then
content_tag( :li, link_to( key, menu[key][‘action’] ) )
end
}
end
It seems using ‘menu.keys.each{|key|’ in a helper will render the key to
the view.
I want to just use key to build the content_tag.
Anyone have a suggestion?
Thanks
Andy