user3040171
user3040171

Reputation: 23

Immutable vs mutable

I do not understand what is going on in the line
print buggy_logger << "\n" # <- This insertion is the bug. Why is that the variable status changes when the above line is called? I am following this website http://www.reactive.io/tips/2009/01/11/the-difference-between-ruby-symbols-and-strings/

status = "peace"

 buggy_logger = status

 print "Status: "
 print buggy_logger << "\n" # <- This insertion is the bug.

def launch_nukes?(status)
  unless status == 'peace'
   return true
  else
return false
 end
end

print "Nukes Launched: #{launch_nukes?(status)}\n"

OUTPUT IS:

=> Status: peace

=> Nukes Launched: true

Upvotes: 0

Views: 93

Answers (2)

Rots
Rots

Reputation: 5586

Your question is "why does the variable change?"

The answer is because buggy_logger holds a reference to status. Easily proven by inspecting the object_id.

irb(main):001:0> a = "hi"
=> "hi"
irb(main):002:0> a.object_id
=> 24088560
irb(main):003:0> b = a
=> "hi"
irb(main):004:0> b.object_id
=> 24088560
irb(main):005:0>

To create a copy use + or any non-mutating operator. Don't use <<.

irb(main):010:0> c = a + " guys"
=> "hi guys"
irb(main):011:0> c.object_id
=> 26523040
irb(main):012:0>

Upvotes: 2

Wes Foster
Wes Foster

Reputation: 8900

Since status = "peace" is a string, when buggy_logger << "\n" is ran, it's updating the string of buggy_logger (and subsequently, status) to be "peace\n"

Therefore, when the method is ran, it returns true because status != "peace" anymore.

Now, if in the beginning you used a symbol status = :peace, it would not be able to be altered with the "\n" appendage. Therefore, the method would return false because status == :peace

Symbol version:

status = :peace

 buggy_logger = status

 print "Status: "
 #print buggy_logger << "\n" # This is no longer possible. It will cause an error

def launch_nukes?(status)
  unless status == :peace
   return true
  else
return false
 end
end

print "Nukes Launched: #{launch_nukes?(status)}\n"  # <- Returns FALSE

Upvotes: 1

Related Questions