parameter passing - How to pass by reference in Ruby? -


currently i'm developing watcher class in ruby, which, among other things, able find period duration of toggling signal. in general rather simple, problem i'm facing apparently ruby passes parameters value. while researching online found many different discussions "pass value" , "pass reference" is, no actual "how to". coming c/c++ background, me essential part of programming/scripting language.

the relevant parts of class wrote shown below. method watcher::watchtoggling() 1 i'm having trouble with. parameter, avariable should reference value i'm measuring period duration for.

class watcher   @done   @timeperiod    def reset()     @done = false;     @timeperiod = nil;   end    def watchtoggling(avariable, atimeout=nil)     oldstate = avariable;     oldtime = 0;     newtime = 0;      timeout(atimeout)do       while(!@done)         newstate = avariable;         if(newstate != oldstate)           if(newstate == 1)             # rising edge             if(oldtime != 0)               # there rising edge before,               # can calculate period               newtime = time.now();               @timeperiod = newtime - oldtime;               @done = true;             else               # if there no previous rising edge,               # set time of 1               oldtime = time.now();             end           end           oldstate = newstate;         end       end     end      puts("watcher: done.")   end    def isdone()     return @done;   end    def gettimeperiod()     return @timeperiod;   end end 

is there way @ in ruby pass reference? , if not, there alternatives solve problem?

ruby strictly pass-by-value, means references in caller's scope immutable. mutable within scope, since can assign them after all, don't mutate caller's scope.

a = 'foo'  def bar(b)   b = 'bar' end  bar(a)  # => 'foo' 

note, however, object can mutated if reference cannot:

a = 'foo'  def bar(b)   b << 'bar' # change: mutate object instead of reference   b = 'baz' end  bar(a)  # => 'foobar' 

if object passed immutable, too, there nothing can do. possibilities mutation in ruby mutating reference (by assignment) or asking object mutate (by calling methods on it).

you can return updated value method , have caller assign reference:

a = :foo  def bar(b)   :"#{a}bar" end  c = bar(a)  c # => :foobar 

or can wrap immutable object in mutable 1 , mutate mutable wrapper:

a = [:foo]  def bar(b)   b[0] = :bar end  bar(a)  # => [:bar] 

[this same thing second example above.]

but if can't change anything, stuck.


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -