0

I've tried to insert some Values into this hash were every key is an array but when I print all result just the last value

def self.hash_builder(query)

       statistic = Hash.new { |hash, key| hash[key] = [] }    

          if !query.empty?

            query.each do |q|

              statistic[:sell].push(q.total_sell.to_i)
              statistic[:price].push(q.total_price.to_f)

            end
          else
            statistic[:sell].push(0)
            statistic[:price].push(0.0)

          end

        return statistic
end

I call this method after make a query, and I send to this the query with the new params, but every time i see inside this hash just the last query value

THIS IS THE RESULT

right output

5
  • 1
    Works for me. Can you show the value of query at the top of the method? Commented Dec 2, 2015 at 1:06
  • Try statistic[:sell] << q.total_sell.to_i. Commented Dec 2, 2015 at 1:08
  • already try this but overwrites the values every time Commented Dec 2, 2015 at 1:14
  • Please show the output of puts query.inspect or similar (in text); not a screenshot of your app, as we don't know what you did to produce the screenshot. Commented Dec 2, 2015 at 1:19
  • @Gene: Array#push and Array#<< are almost identical, where one works the other should too (except for the valence of push). Commented Dec 2, 2015 at 1:20

1 Answer 1

1

I'll answer here because the comment section doesn't allow enough room. You're wrong about <<. It ought to work fine.

$ irb
irb(main):001:0> s = Hash.new {|h, k| h[k] = [] }
=> {}
irb(main):002:0> s[:sell] << 1
=> [1]
irb(main):003:0> s[:sell] << 2
=> [1, 2]
irb(main):004:0> s[:sell]
=> [1, 2]
irb(main):005:0> s[:price]
=> []

But push should work, too.

irb(main):006:0> s[:sell].push(3)
=> [1, 2, 3]
Sign up to request clarification or add additional context in comments.

1 Comment

I see the problem, every times when i call the model I re-initialize the Hash for that i delete every times the old values. Thanks !!! A lot !!! with your terminal screen I see my error !!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.