简体   繁体   中英

Ruby classes and methods changes variables

I'm trying Ruby and can't understand some things. I have some class:

class Some_class
  def method_a
    var = '123' 
    method_b(var)
  end

  def method_b(var)
     ...
     return var
  end
end

method_b changes var and returns it (something like a md5 hash if you want). And here the thing that i missunderstand:
if i do this

def method_a
  var = '123'
  method_b(var)
  method_b(var)
  b = method_b(var)
  return (b == var)
end

then method_a returns true. And i have to do .dup to avoid it. Why is it happening? Methods in Ruby are objects too and var contains just link on method_b? Or happening something else?

Thank you and sorry for my English, thats not my native language.

You pass var as a reference to the object to method_b . This object is modified inside of this method. That's why var (containing still reference to the same object) returns modified value after method_b call.

I have tried the following codes, you can see the results

ROR: 058 > def method_a
059?>          var = '123' 
060?>          b=method_b(var)
061?>          var == b
062?>      end
 O/P => :method_a 
ROR: 063 > 
064 >      def method_b(var)
065?>          var = 'shiva'
066?>          return var
067?>      end
 O/P => :method_b 
ROR: 068 > method_a
 O/P => false 

and

ROR: 069 > def method_a
070?>          var = '123'
071?>          method_b(var)
072?>          method_b(var)
073?>          b = method_b(var)
074?>          return (b == var)
075?>      end
 O/P => :method_a 
ROR: 076 > method_a
 O/P => false 

the results are false in above experiments

  1. The method_b never modifies the variable 'var' in method_a.

  2. You might have problem in logic inside method_b.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM