Reputation: 11
When I try to shorten an array with ''
the output from all other variables is changing too
message = "bot.start"
seperator = message
command = seperator
command[0..3] = ''
message #=> "start"
The output should be "bot.start"
. Ruby should have a problem separating variables from each other. What is wrong?
Upvotes: 0
Views: 58
Reputation: 141588
In the current version Ruby, strings are mutable. That is, you can change an instance of a string.
In your example, message
, command
and separator
are all different variables that point to the same string instance. When you do [0..3] = ''
, you are changing the string that all the variables point to.
If you need to make distinct instances, use dup
to copy the string:
command = seperator.dup
Alternatively, don't modify the string and use APIs that return a new instance of a string:
command = seperator[4..-1]
Upvotes: 1
Reputation: 121
When you execute line 4
command[0..3] = ''
You grabed bot.
and changed to bot.
=> ''
That's why it returns''start
which is start
https://repl.it/repls/BlushingThoughtfulOrigin
Upvotes: 0