红宝石中的常量或类变量? [英] Constants or class variables in ruby?

查看:59
本文介绍了红宝石中的常量或类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用Ruby编程了几个月了,我想知道何时在类变量上使用常量,反之亦然。 (我在Rails中工作,正在考虑模型中的常数。)

I've been programming in Ruby for a few months now, and I'm wondering when it is appropriate to use constants over class variables and vice versa. (I'm working in Rails, thinking about constants in models).

class Category
  TYPES = %w(listing event business).freeze
end

OR

class Category
  @@types = %w(listing event business).freeze
  cattr_reader :types
end

在某些情况下,一个人比另一个人更可取吗?还是只是口味/风格的问题?

Are there circumstances where one is preferable to another? Or is it just a matter of taste/style?

推荐答案

主要是使用CONSTANT表示法,向读者说明清楚。小写字母,冻结的字符串给人的印象是可能是可设置的,迫使某人回去阅读RDoc。

The main thing is that by using the CONSTANT notation, you're making it clear to the reader. the lower case, frozen string gives the impression is might be settable, forcing someone to go back and read the RDoc.

这篇关于红宝石中的常量或类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆