Hudson Silva Hudson Silva - 23 days ago 5
Ruby Question

Error while using array.map(&:gsub)

I'm trying to remove all the

-
from the strings in an array using
map(&:gsub('-',''))
, but I'm having some difficulty to understand why it is not working:

2.2.2 (main)> my_array = [ 'a-b-c', 'd-e-f', 'g-h-i']
=> [
[0] "a-b-c",
[1] "d-e-f",
[2] "g-h-i"
]
2.2.2 (main)> my_array.map(&:gsub('-',''))
SyntaxError: unexpected ',', expecting end-of-input
my_array.map(&:gsub('-',''))
^


But, when I try these, they work

2.2.2 (main)> my_array.map!(&:upcase)
=> [
[0] "A-B-C",
[1] "D-E-F",
[2] "G-H-I"
]

2.2.2 (main)> my_array.map!(&:downcase)
=> [
[0] "a-b-c",
[1] "d-e-f",
[2] "g-h-i"
]

2.2.2 (main)> my_array.map(&:class)
=> [
[0] String < Object,
[1] String < Object,
[2] String < Object
]

2.2.2 (main)> my_array.map{ | element | element.gsub("-", "") }
=> [
[0] "abc",
[1] "def",
[2] "ghi"
]


Does anyone know why I'm getting this error with
map(&:gsub( "-", ""))
?

Answer

You can't pass a method that way. You should do the following:

my_array.map{ |a| a.gsub('-','') }

About a proper usage of ampersand you can read here: Ruby ampersand colon shortcut

Comments