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
 
Ad

Advertisements

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
 
Ad

Advertisements

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
 

Top