Topic: Trouble with hash.each

Hi!  I have this piece of ruby in a view in my app:

<%= h = { "a" => 100, "b" => 200 }
   h.each {|key, value| puts "#{key} is #{value}" }%>

but it prints out this:

a100b200

instead of

a is 100
b is 200

so... where is the " is " part going?!

thanks in advance, first post! Whew. Dave.

Re: Trouble with hash.each

NEVER use puts in Rails, it causes havoc as you are sending data to the current out Which may or may not be the browser, a log file or the console

Plus you are already sending output to the browser because you are using an opening erb tag with an = sign (<%=) which essentially translates into English as 'Get the text from this ruby code and convert it into an HTML string'

You could do the following

<% h = { "a" => 100, "b" => 200 }%>
<%  h.each do |key, value| %>
   <%= "#{key} is #{value}, "}%>
<%end%>

But  the really glaringly obvious mistake is that you are thinking this code belongs anywhere near the view in the first place.
The definition of h is business logic and could change at any time so it firmly belongs in the middle tier. If there is not a logical model that ths code fits then make a module or a class
something like
h.rb

  class H
    def self.get_hash
      { "a" => 100, "b" => 200 }
    end
  end

Then in your controller action or in a view helper module you can just call @h = H.get_hash
The use the @h instance variable to loop through the results in your view

Hope that helps

What you want and what you need are too often not the same thing!
When your head is hurting from trying to solve a problem, stop standing on it. When you are the right way up you will see the problem differently and you just might find the solution.
(Quote by me 15th July 2009)

Re: Trouble with hash.each

Hi James, thanks so much for the reply, fixed my immediate problem and taught me something...

: )

Cheers, Dave