I am trying to create a new array where elements of the original array are replaced with their corresponding values in the hash. I want to compare every element in arr to the key in hash and if they are equal shovel them into the arr and return it at the end. Why is my code not working and how can I access/return the key value of the respective entry in hash, not only the value pointed to by the key? If you get what I am saying.
def element_replace(arr, hash)
count = []
#hash.each {|key, value|
for i in arr do
if i == hash.key
count << value
else
count << i
end
end#}
return count
end
arr1 = ["LeBron James", "Lionel Messi", "Serena Williams"]
hash1 = {"Serena Williams"=>"tennis", "LeBron James"=>"basketball"}
print element_replace(arr1, hash1) # => ["basketball", "Lionel Messi", "tennis"]
puts
arr2 = ["dog", "cat", "mouse"]
hash2 = {"dog"=>"bork", "cat"=>"meow", "duck"=>"quack"}
print element_replace(arr2, hash2) # => ["bork", "meow", "mouse"]
puts
CodePudding user response:
Ruby's fetch
would be a technique to get your desired result:
> players = ["LeBron James", "Lionel Messi", "Serena Williams"]
=> ["LeBron James", "Lionel Messi", "Serena Williams"]
> sports_data = {"Serena Williams"=>"tennis", "LeBron James"=>"basketball"}
=> {"Serena Williams"=>"tennis", "LeBron James"=>"basketball"}
> players.map { |player| sports_data.fetch(player, player) }
=> ["basketball", "Lionel Messi", "tennis"]
CodePudding user response:
You can map the array to hash keys or keep the array element itself: if the key is missing (return nil
) keep the array element:
arr1.map { |k| hash1[k] || k }
#=> ["basketball", "Lionel Messi", "tennis"]