views:

39

answers:

2

Hi All,

I want to create a alias method in ruby and pass parameters to this. I managed to do the following

class User
  def say_name
    puts "I'm sameera"
  end
end

class User
  alias :tell_name :say_name
  def say_name
    puts "I'm sameera gayan"
    tell_name
  end
end

user = User.new
user.say_name

and it gives me the out put as

I'm sameera gayan I'm sameera

But now i want to pass my name as a parameter to the first 'say_name' method. So the new code will be like

class User
  def say_name(name)
    puts "#{name}"
  end
end

class User
  alias :tell_name :say_name(name)
  def say_name(name)
    puts "I'm sameera gayan"
    tell_name(name)
  end
end

user = User.new
user.say_name("my new name")

But now this doesn't work (passing parameter to alias method). So my question is how to pass parameters to an alias method.

I hope this question is clear to you. Thanks in advance

cheers

sameera

A: 

Hi, I'm learning Ruby. So when I saw this question I decided to try it. Though I have yet to learn about aliasing methods in detail I came across a solution. Don't know if it is the way it should be done. And can't say why it is so yet. May be in a few days after I have learn't in depth I'll add it. For now, here is a working solution.

class User
  attr_accessor :name
  def say_name
    puts "#{name}"
  end
end

class User
  alias :tell_name :say_name
  def say_name
    puts "I'm sameera gayan"
    tell_name
  end
end

user = User.new
user.name = "Sameera"
user.say_name 

This qtn also helped me in the process.

Christy John
This looks correct. Aliases don't take parameters, as sameera tried. They just make another name for the method.
AboutRuby
hi ChristyThanks for the reply. But in my case I'm trying to override an active_support method. because of that I cant add an attribute or do any changes. (In my example first User class)thankssameera
sameera207
+1  A: 

I tried this one and came to this solution

class User

        def say_name(name)

              puts "#{name}"

        end

end

class User

        alias :tell_name :say_name

        def say_name(name)

              puts "Hi"

              tell_name(name)

        end

end

user = User.new

user.say_name("Rohit")

The reason this is working because we cannot pass arguments to aliases. And that is what you were trying to do.

Rohit
Hi Rohit, this works thanks
sameera207