在 Ruby 中创建属性别名的最佳方法是什么? [英] What is the best way to create alias to attributes in Ruby?
本文介绍了在 Ruby 中创建属性别名的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Ruby 中为实例属性创建别名的最佳方法是什么(我没有使用 rails 或任何 ruby gem,只是,Ruby).
例如,给定下面的类,我如何为 :student_name
属性访问器创建别名?
What is the best way to create an alias to a instance atribute in Ruby (I'm not using rails or any ruby gem, just, Ruby).
For example given the class below, how can I create an alias to the :student_name
attribute accessors?
class Student
attr_accessor :student_name
alias :name :student_name #wrong
end
s = Student.new
s.student_name = "Jordan"
puts s.name # --> Jordan
s.name = "Michael" # --> NoMethodError: undefined method `name=' for #<Student:0x572394> ...
谢谢各位!
推荐答案
add
alias :name :student_name # not wrong, only for getter
alias :name= :student_name= # add this for setter
alias :name? :student_name? # add this for boolean
这篇关于在 Ruby 中创建属性别名的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文