On 15 February 2011 18:26, Paul Bergstrom <li...@ruby-forum.com> wrote:
> Hmm. This should output a string in view but it doesn't:
>
> <% h = { "a" => 100, "b" => 200 } %>
> <%= h.each {|key, value| puts "#{key} is #{value}" } %>

It certainly won't do what you think it should....

As has already been pointed out, the .each method on a hash returns
the original hash, so your code is going to put some text onto the
console (not the same as rendering in the browser) and then render the
original hash in the browser.

You *probably* want something more like:
  <% test_hash = { "a" => 100, "b" => 200 } %>
  <% test_hash.each do |key, value| %>
    <%=puts "#{h key} is #{h value}" %>
  <% end%>

Or use .inject to collect up all the return values of the block and
render that...

Check out the api for lots more handy Hash/Enumerable methods, and
*exactly* how they should work. I can heartily recommend playing with
them in a console window to get to grips with how they work.

http://ruby-doc.org/core/classes/Hash.html
http://ruby-doc.org/core/classes/Enumerable.html

PS "h" is a bad name for a variable, and not idiomatic. It would
replace the "h" shortcut for html encoding (assuming Rails 2.x) and
isn't very descriptive of it's intention

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to