How does this ruby custom accessor work

Posted by ennuikiller on Stack Overflow See other posts from Stack Overflow or by ennuikiller
Published on 2010-12-31T02:49:40Z Indexed on 2010/12/31 2:54 UTC
Read the original article Hit count: 370

So the method below in class_eval dynamically creates accessors for attributes defined at runtime. It can be used, for example, to create configuration objects with attributes read from a config file (and unknown until runtime). I understanding all of it except for the else branch. If I am correct the else branch returns the attribute value (val[0]) if there is one value passed in *val. However the way its written I would expect it to return an array (val) if there is more then one value passed in *var. In particular, if I have something like the following:

value = 5

then from reading the code I would expect "#{@value}" to be [=,5]. However "#{@value}" returns 5 and not the array [=,5]. How is this possible?

class Module
    def dsl_accessor(*symbols)
        symbols.each do |sym|
            class_eval %{
                def #{sym}(*val)
                    if val.empty?
                        @#{sym}
                    else
                         @#{sym} = val.size == 1 ? val[0] : val
                    end
                end
            }
        end
    end
end

© Stack Overflow or respective owner

Related posts about ruby

Related posts about metaprogramming