Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Array.inject issue -- Can't see it

Tags:

ruby

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
like image 936
Jeff Ancel Avatar asked Dec 03 '22 07:12

Jeff Ancel


2 Answers

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
like image 183
glenn mcdonald Avatar answered Jan 19 '23 05:01

glenn mcdonald


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 }

like image 35
ezpz Avatar answered Jan 19 '23 05:01

ezpz