I'm trying to conditionally map an array I have:
Array that looks like [ "a", "b", "c" ]
I want to map it inline (using map!) to change anything that matches /b/ and change it to "bb". This doesn't seem to work though, it doesn't seem to be changing the array.
I want it to look like this [ "a", "bb", "c" ]
define the array:
irb(main):001:0> a = [ "a", "b", "c" ]
=> ["a", "b", "c"]
Try with a select chained to a map!, and it shows the changed value for the one element, and it didn't change the original array.
irb(main):002:0> a.select { |e| e =~ /b/ }.map! { |e| e = "bb" }
=> ["bb"]
irb(main):003:0> p a.inspect
"[\"a\", \"b\", \"c\"]"
So I tried doing the same thing, but assigning it to a new array, this only creates an array with any changed elements - not what I want
irb(main):004:0> cc = a.select { |e| e =~ /b/ }.map! { |e| e = "bb" }
=> ["bb"]
irb(main):005:0> p cc.inspect
"[\"bb\"]"
=> nil
What am I missing here? I'm missing some Ruby fundamental knowledge here I think.
You call
selectona, which returns new instance ofArray, on which in the next step you callmap!, modifying this new instance (not the original one). To achieve what you want, you can do: