在 Ruby 中创建属性别名的最佳方法是什么?

编程入门 行业动态 更新时间:2024-10-24 21:30:20
本文介绍了在 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 中创建属性别名的最佳方法是什么?

本文发布于:2023-11-28 06:39:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641328.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:别名   属性   方法   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!