gpt4 book ai didi

ruby-on-rails - 是否可以为 to_s 起别名?

转载 作者:数据小太阳 更新时间:2023-10-29 08:22:57 24 4
gpt4 key购买 nike

我不想在我的模型中覆盖 to_s,而是想将它别名为一个名为 full_name 的现有方法。

aliasalias_method 似乎都没有按预期工作。

使用别名

class Person < ActiveRecord::Base

# ... other model code.

alias to_s full_name

def full_name
"#{first_name} #{last_name}"
end
end

# In Terminal
> Person.last.to_s #=> "#<Person:0x007fa5f8a81b50>"

使用alias_method

class Person < ActiveRecord::Base

# ... other model code.

alias_method :to_s, :full_name

def full_name
"#{first_name} #{last_name}"
end
end

# In Terminal
> Person.last.to_s #=> "#<Person:0x007fa5f8a81b50>"

最佳答案

想通了...

aliasalias_method 需要在您作为别名的方法之后

所以以下两个都可以正常工作:

使用别名

class Person
def full_name
"#{first_name} #{last_name}"
end

alias to_s full_name
end

# In Terminal
> Person.last.to_s #=> "Don Draper"

使用alias_method

class Person
def full_name
"#{first_name} #{last_name}"
end

alias_method :to_s, :full_name
end

# In Terminal
> Person.last.to_s #=> "Don Draper"

希望这对其他人有帮助。

关于ruby-on-rails - 是否可以为 to_s 起别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23225145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com