object - Local variables and methods with the same name in Ruby? -


def gen_times(factor)   return proc.new {|n| n*factor} end  gen_times.class # argumenterror 0 1 gen_times(3).class # proc gen_times = 2 gen_times.class # fixnum times3 = gen_times(3) # normal, working proc 

the first gen_times.class gives argumenterror, assume returns class name of gen_times's return value, confirmed in next line.

but then, assign gen_times, , becomes fixnum. however, can still use gen_times return procs.

i recall fixnum objects have immediate values, , object used in assignment, rather reference it.

so, right gen_times fixnum object refers method?

in ruby can have local variables , methods same name. has complications example setter methods in classes:

class test   def active     @active   end    def active=(value)     @active = value   end    def make_active     active = true   end end  t1 = test.new t1.active = true t1.active #=> true  t2 = test.new t2.make_active t2.active #=> nil 

code t1 object return expected result, code t2 returns nil, because make_active method creating local variable , not calling active= method. need write self.active = true make work.

when write gen_class, ruby tries access local variable, if not defined ruby tries call method. can call method explicit writing gen_class().


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -