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
    "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
     
    Sam Kong, Apr 22, 2005
    #1
    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 g.call or g[].

    -austin
     
    Austin Ziegler, Apr 22, 2005
    #2
    1. Advertisements

  3. Sam Kong

    Malte Milatz Guest

    Sam Kong:
    What is wrong about alias_method? Otherwise:

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

    Malte
     
    Malte Milatz, Apr 22, 2005
    #3
  4. Sam Kong

    Luca Pireddu Guest

    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
     
    Luca Pireddu, Apr 23, 2005
    #4
  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
     
    Sam Kong, Apr 23, 2005
    #5
    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.