Jesús Gabriel y Galán
8/20/2008 7:27:00 AM
On Tue, Aug 19, 2008 at 10:23 PM, Lex Williams <etaern@yahoo.com> wrote:
> 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 ?
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.