D
Derek Cannon
I'm new to Ruby. I'm trying to add a method to the Array class that adds
the functionality of gsub! to arrays.
Looking around the internet, I found a keyword know as detect { } which
allows me to get the elements of the array. Testing it, I find the
following code:
class Array
def test
detect { |x| puts x}
end
end
...prints out all the elements in the array. However, when I try:
class Array
def gsub!(pattern, replacement)
detect { |x|
x.gsub!(pattern, replacement)
}
end
end
...the result is only a modification of the first element in the array.
For example, the following code:
x = ["Hello", "there", "world", "how", "are", "you?"]
x.gsub!(/[aeiou]/, "_")
puts x
outputs only:
H_ll_
there
world
how
are
you?
Does anyone know what I'm doing wrong?
the functionality of gsub! to arrays.
Looking around the internet, I found a keyword know as detect { } which
allows me to get the elements of the array. Testing it, I find the
following code:
class Array
def test
detect { |x| puts x}
end
end
...prints out all the elements in the array. However, when I try:
class Array
def gsub!(pattern, replacement)
detect { |x|
x.gsub!(pattern, replacement)
}
end
end
...the result is only a modification of the first element in the array.
For example, the following code:
x = ["Hello", "there", "world", "how", "are", "you?"]
x.gsub!(/[aeiou]/, "_")
puts x
outputs only:
H_ll_
there
world
how
are
you?
Does anyone know what I'm doing wrong?