Nuby Question - How do you assign a function itself?

S

Sam Kong

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
 
A

Austin Ziegler

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
 
M

Malte Milatz

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
 
L

Luca Pireddu

Austin said:
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
 
S

Sam Kong

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top