Nuby Question - How do you assign a function itself?

Discussion in 'Ruby' started by Sam Kong, Apr 22, 2005.

  1. Sam Kong

    Sam Kong Guest

    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

    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.

    Sam Kong, Apr 22, 2005
    1. Advertisements

  2. 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 or g[].

    Austin Ziegler, Apr 22, 2005
    1. Advertisements

  3. Sam Kong

    Malte Milatz Guest

    Sam Kong:
    What is wrong about alias_method? Otherwise:

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

    Malte Milatz, Apr 22, 2005
  4. Sam Kong

    Luca Pireddu Guest

    Another alternative may to to use Proc objects
    f = { |x| x*x }
    g = f

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

    f =
    g = f

    Hope that helps

    Luca Pireddu, Apr 23, 2005
  5. Sam Kong

    Sam Kong Guest

    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 Kong, Apr 23, 2005
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.