0

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?

3
  • 1
    I don't know Ruby, but usually use of = means that you're referring to the same object. If that's the case, command = seperator makes command literally the same object as seperator. You'll likely need to make a copy of seperator before assigning if you want them to act separately. Commented Apr 7, 2018 at 21:31
  • 1
    Why do you think "[t]he output should be "bot.start"? Commented Apr 9, 2018 at 5:01
  • By the way, your message is a string, not an array. Commented Apr 9, 2018 at 5:01

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.