I am very new to Ruby, and programming in general. Firstly, I have the below code:
hashy = {"a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 6, "f" => 6}
array = ["a", "b", "c"]
string = "df"
array.push (string.split(//))
puts array
test = array.map {|a| hashy.select {|k,v| a == k}}
puts test
This code successfully maps ‘a’, ‘b’ and ‘c’ to the hash, and populates test with the keys and values from the hash.
This always works for a pre-defined array. However if I add to the array from a string (in this case the string “df”, or create an array from a string, it no longer maps the array values to the hash, and I can’t see why. I’ve looked at different ways of populating the array with the string values, but each time get the same problem.
As far as I can see “df” should also be mapping to the hash.
Any help would be greatly appreciated.
It’s because you pushing
string.split(//)array toarrayas one object, so you have one array element among the numbers inarrayas result.To avoid this, you can use array concatenation, for example