Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using functions to populate Ruby hashes

Tags:

ruby

hash

I get the following output from the code:

arr = [1,2,3]
gdu = {}
gdu = {
      "b" => 4,
      "c" => arr,
      "d" => arr.map {|x| x * gdu["b"].to_i },
      "e" => gdu["b"].to_i
}
gdu.default = "value does not exit in hash gdu"
gdu # => {"b"=>4, "c"=>[1, 2, 3], "d"=>[0, 0, 0], "e"=>0}

Why does the code here have this output?

like image 609
Jake Cooper Avatar asked Sep 19 '26 19:09

Jake Cooper


1 Answers

You are setting the whole hash’s value at once, as one atomic operation. RHO uses the current version of gdu, which is an empty hash at the moment.

To achieve what you wanted, assign values step by step:

gdu = {}
gdu["b"] = 4
gdu["c"] = arr
gdu["d"] = arr.map { |x| x * gdu["b"] } # `to_i` is redundant
gdu["e"] => gdu["b"]
like image 131
Aleksei Matiushkin Avatar answered Sep 21 '26 11:09

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!