簡體   English   中英

是否可以為 to_s 取別名?

[英]Is it possible to alias to_s?

我不想在我的模型中覆蓋to_s ,而是想將其別名為一個名為full_name的現有方法。

aliasalias_method似乎都沒有按預期工作。

使用alias

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需要跟你別名的方法之后

所以以下兩個都可以正常工作:

使用alias

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"

希望這對其他人有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM