Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass parameters to an alias method in ruby

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

like image 650
sameera207 Avatar asked Feb 27 '23 09:02

sameera207


2 Answers

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.

like image 50
Rohit Avatar answered Mar 12 '23 02:03

Rohit


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.

like image 37
Christy John Avatar answered Mar 12 '23 04:03

Christy John