Ruby/Rails 中的类方法与常量 [英] Class method vs constant in Ruby/Rails

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

问题描述

我正在实现一个包含集合的硬编码下拉列表的表单,我想知道最好的解决方案是什么,我知道下面公开的两种方式都可以工作,但我仍然按以下方式操作:

I was implementing a form that includes a hard-coded dropdown for a collection and I was wondering what would be the best solution, I know both ways exposed below work, still I did as follows:

class Example

  # Options for Example.
  self.options
    [ 'Yes', 'No', 'Not sure' ]
  end
end

Example.options 调用,但我知道也可以执行以下操作:

which is called by Example.options, but I know it is possible to do as follows as well:

class Example

  # Options for Example.
  OPTIONS = [ 'Yes', 'No', 'Not sure' ]
end

将使用 Example::OPTIONS 调用.

问题是,这些是好方法还是根本不重要?

The question is, is any of these the good way or it just doesn't matter at all?

推荐答案

后者更好.如果是方法,每次调用都会创建一个新的数组和新的字符串,浪费资源.

The latter is better. If it were a method, a new array and new strings will be created every time it is called, which is a waste of resource.

这篇关于Ruby/Rails 中的类方法与常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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