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
  • 160,959
  • 41
  • 265
  • 366
Joe Ainsworth
  • 551
  • 6
  • 19

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,407
  • 7
  • 49
  • 98
-1

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

sawa
  • 160,959
  • 41
  • 265
  • 366