1

Why does calling the mess_with_vars method not modify the value of the variables shown within?

def mess_with_vars(one, two, three)
  one = "two"
  two = "three"
  three = "one"
end

one = "one"
two = "two"
three = "three"

mess_with_vars(one, two, three)

puts "one is: #{one}"
puts "two is: #{two}"
puts "three is: #{three}"
sawa
  • 165,429
  • 45
  • 277
  • 381
Joe Ainsworth
  • 571
  • 1
  • 6
  • 20

2 Answers2

1

Ruby is pass-by-value (Is Ruby pass by reference or by value?), so you can definitely modify the value of objects, and you will see its effects outside a method.

Consider these:

def mess_with_vars(one, two, three)
  one.gsub!('one','two')
  two.delete!("wo")
  three.replace "one"
end

All above modify the arguments.

Community
  • 1
  • 1
Filip Bartuzi
  • 5,711
  • 7
  • 54
  • 102
-1

Because the scope of a local variable initialized in a method definition is the method definition.

sawa
  • 165,429
  • 45
  • 277
  • 381