Reputation: 25
I want a string which eliminates every "x, X". For example Xylophone -> ylophone, Xbox -> bo. This is my recent code:
class String
def xaway
s = self.split("")
return ( s - ["xX"] ).join
end
end
What is wrong?
Upvotes: 0
Views: 46
Reputation: 114178
What is wrong?
Splitting the string by ""
returns an array of characters, e.g.:
"Xbox".split("")
#=> ["X", "b", "o", "x"]
And Array#-
expects an array of elements to remove. But if you pass ["Xx"]
it tries to remove the element "Xx"
which doesn't exist in the array:
["X", "b", "o", "x"] - ["Xx"]
#=> ["X", "b", "o", "x"]
What you want is ["X", "x"]
:
["X", "b", "o", "x"] - ["X", "x"]
#=> ["b", "o"]
The whole code:
class String
def xaway
(split("") - ["X", "x"]).join
end
end
A little more concise:
class String
def xaway
(chars - %w[X x]).join
end
end
Or, using String#delete
:
class String
def xaway
delete("Xx")
end
end
Note that you shouldn't modify Ruby's core classes.
Upvotes: 3