Can any one tell me why the following:
['a', 'b'].inject({}) {|m,e| m[e] = e }
throws the error:
IndexError: string not matched from (irb):11:in `[]=' from (irb):11:in `block in irb_binding' from (irb):11:in `each' from (irb):11:in `inject' from (irb):11 from C:/Ruby192/bin/irb:12:in `<main>'
whereas the following works?
a = {} a["str"] = "str"
Creating a Hash In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.
At the end of the process, inject returns the accumulator, which in this case is the sum of all the values in the array, or 10. In this case, we are defaulting our accumulator to an empty hash, then populating it each time the block executes.
Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.
This article will demonstrate the different uses of the inject method in Ruby. The inject method takes a block of two arguments. The first argument is an accumulator, the running total of the expression being evaluated, and the second is the current array item. In the example above, the initial value is 0.
The second form of initializing a Hash is by passing in an object. This object will then be used as the default value. From the docs: If obj is specified, this single object will be used for all default values. I most commonly reach for this style when using a hash as a counter.
The inject method takes a block of two arguments. The first argument is an accumulator, the running total of the expression being evaluated, and the second is the current array item. In the example above, the initial value is 0.
It’s not too hard- Ruby is very similar to Java and C. If you’re familiar with programming in Java or C, you should be able to learn Ruby in no time. The INJECT keyword in Ruby calls the INJECT method that is most commonly used with arrays, with the enumerable module and with converting array elements into hashes.
Your block needs to return the accumulating hash:
['a', 'b'].inject({}) {|m,e| m[e] = e; m }
Instead, it's returning the string 'a' after the first pass, which becomes m
in the next pass and you end up calling the string's []=
method.
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