Ruby Forum Ruby > some method help ... not really sure about proper title

Posted by vhaerun vh (vhaerun)
on 19.08.2008 22:26
Hi guys!

I'm kinda new to ruby , and was wondering about the following stuff ,
assume the following code :

Shoes.app {
  button("Press Me") { alert("You pressed me") }
}

how could I write code like that , so that when I call a method like
button , I don't have to put an object or a class name in front of it .

To give another example , let's assume the following code :

class Whatever
   attr_accessor :value

   def initialize
      yield self
   end

   def some_method
      puts "some method"
   end

end

I would like to do the following ( if it's possible ) :

w = Whatever.new do |whatever|
        some_method
        value = 20
end

puts w.value # this should output 20

Is this possible , without adding those methods to Object ?

Thank you very much!
Posted by Jesús Gabriel y Galán (Guest)
on 20.08.2008 09:30
(Received via mailing list)
On Tue, Aug 19, 2008 at 10:23 PM, Lex Williams <etaern@yahoo.com> wrote:
> button , I don't have to put an object or a class name in front of it .
>   def some_method
> end
>
> puts w.value # this should output 20
>
> Is this possible , without adding those methods to Object ?

Hi, if you use the following you can call certain methods like you want.

 class Whatever
   attr_accessor :value

   def initialize &blk
      instance_eval &blk
   end

   def some_method
      puts "some method"
   end
 end

This will allow to do:

w = Whatever.new {some_method}

The only exception are the xxx= methods. This won't work:

w = Whatever.new {value = 20}

The reason is that value= methods have to be called as self.value=20
within the class, because it's
the only way for the interpreter to understand that you want a method
call and not a local variable to the
function. You could do:

w = Whatever.new {self.value = 20}

That works.

Hope this gives you some other ideas...

Jesus.
Posted by vhaerun vh (vhaerun)
on 20.08.2008 09:42
That was exactly what I was looking for!
Thank you very much !