Modify the line string.gsub(string, string + "s")
to string.gsub!(string, string + "s")
. It will work.
String#gsub
works on the copy of the receiver, where as String.gsub!
works on the receiver itself.
Pregunta
I am studying for an exam tomorrow. One of the previous questions was to define a method to add a e
to an array element (array of symbols) if the element ended with a
or add an s
if it ended with i
.
Without using gsub or sub I can do this fine:
arbitrary = [:alpha, :beta, :kappa, :phi]
p arbitrary
def pluralise (array)
manipulate = []
array.each {|member|
string = member.to_s
last_char = string[-1,1]
if last_char == "a" then
string = string + "e"
manipulate << string.to_sym
end
if last_char == "i" then
string = string + "s"
manipulate << string.to_sym
end
}
manipulate
end
new_arbitrary = pluralise(arbitrary)
p new_arbitrary
However, attempting this with gsub
or sub
does not change the array:
arbitrary = [:alpha, :beta, :kappa, :phi]
p arbitrary
def pluralisesub (array)
manipulate = []
array.each {|member|
string = member.to_s
last_char = string[-1,1]
if last_char == "a" then
string.gsub(string, string + "s")
manipulate << string.to_sym
end
if last_char == "i" then
string.gsub(string,string + "s")
manipulate << string.to_sym
end
}
manipulate
end
new_arbitrary = pluralisesub(arbitrary)
p new_arbitrary
Does anybody have any ideas what is going wrong here?
Thanks
Solución
Modify the line string.gsub(string, string + "s")
to string.gsub!(string, string + "s")
. It will work.
String#gsub
works on the copy of the receiver, where as String.gsub!
works on the receiver itself.
Otros consejos
You can do the entire find and replace on in array in a map and case statement.
[:alpha, :beta, :kappa, :phi].map do |v|
v = v.to_s
case v[-1]
when 'a' then v + 'e'
when 'i' then v + 's'
else v
end
end