[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Nuby Question - How do you assign a function itself?

Sam Kong

4/22/2005 5:31:00 PM

Hi, all!

I've been with Ruby for a year now and am still a newbie...:-(
(I wish I were using Ruby at work.)

My question is about assigning a function to a variable.

def f
"f"
end

g = f #assigns the return value of f to g.

What I want is to assign the function to g so that I can call g instead
of f.

All I could find was
alias :g :f

I am sure there's another way to do it.

Thanks.
Sam

4 Answers

Austin Ziegler

4/22/2005 5:40:00 PM

0

On 4/22/05, Sam Kong <sam.s.kong@gmail.com> wrote:
> What I want is to assign the function to g so that I can call g instead
> of f.
>
> All I could find was
> alias :g :f

You can't.

You can, however do:

g = method(:f)

You can't just do g, though, because g is now a method object. You
need to do either g.call or g[].

-austin
--
Austin Ziegler * halostatue@gmail.com
* Alternate: austin@halostatue.ca



Malte Milatz

4/22/2005 5:48:00 PM

0

Sam Kong:
> What I want is to assign the function to g so that I can call g instead of
> f.

What is wrong about alias_method? Otherwise:

def g(*args, &block)
f(*args, &block)
end

Malte

Luca Pireddu

4/22/2005 11:37:00 PM

0

Austin Ziegler wrote:

> On 4/22/05, Sam Kong <sam.s.kong@gmail.com> wrote:
>> What I want is to assign the function to g so that I can call g instead
>> of f.
>>
>> All I could find was
>> alias :g :f
>
> You can't.
>
> You can, however do:
>
> g = method(:f)
>
> You can't just do g, though, because g is now a method object. You
> need to do either g.call or g[].
>
> -austin

Another alternative may to to use Proc objects
f = Proc.new { |x| x*x }
g = f
g.call(2)

Or maybe a functor-style construct
class Raise
def initialize(exponent)
@exponent = exponent
end
def call(x)
  return x ** @exponent
end
end

f = Raise.new(3)
g = f
g.call(2)

Hope that helps

Luca

Sam Kong

4/23/2005 6:21:00 AM

0

Thank you for the reply.
There's nothing wrong with alias.
I just wanted to make sure that it's the best way to do it.

I also thank other repliers.

Sam