ruby中如何将参数传递给别名方法
我想在 ruby 中创建一个别名方法并将参数传递给它。我设法做了以下事情
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
,它给了我输出,因为
我是 Sameera gayan 我是 Sameera
但现在我想将我的名字作为参数传递给第一个“say_name”方法。所以新代码将类似于
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")
但现在这不起作用(将参数传递给别名方法)。所以我的问题是如何将参数传递给别名方法。
我希望你清楚这个问题。预先感谢
欢呼
Sameera
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我尝试了这个并得出了这个解决方案
之所以有效,是因为我们无法将参数传递给别名。这就是你想要做的。
I tried this one and came to this solution
The reason this is working because we cannot pass arguments to aliases. And that is what you were trying to do.
我正在学习 Ruby。所以当我看到这个问题时我决定尝试一下。尽管我还没有详细了解别名方法,但我遇到了一个解决方案。不知道这是不是应该这样做。还不能说为什么会这样。可能在我深入学习后几天我会添加它。目前,这是一个可行的解决方案。
这个 qtn 也有帮助我在这个过程中。
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.
This qtn also helped me in the process.
我粘贴了一些可以帮助您的别名方法组合
I am pasting some combination of alias method that can help you