I am trying to store values from an array, to a hash (array value is the key, value just 0). Here is my code. Any ideas?
[1, 2, 3, 4].inject({}) {|result, e| result[e] = 0}
This is the error I am getting.
oMethodError: undefined method `[]=' for 0:Fixnum
from (irb):1
from (irb):1:in `inject'
from (irb):1:in `each'
from (irb):1:in `inject'
from (irb):1
from :0
The "; result" thing works fine, but as a matter of taste, I prefer this way:
[1,2,3,4].inject({}) {|result,e| result.merge!(e=>0)}
If this is in performance-critical code, though, taste has its price. Here's a quick benchmark doing this operation a million times.
In Ruby 1.8.5
merge: 22s
merge!: 14s
; result: 9s
In Ruby 1.9.1
merge: 18s
merge!: 11s
; result: 5s
The issue is that result[e] = 0
returns the result of the operation, namely 0, and that is carried to the next iteration where you try to call []=
on it. You can get past this by doing the following:
[1, 2, 3, 4].inject({}) {|result, e| result[e] = 0; result }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With