相关疑难解决方法(0)

ruby中的常量或类变量?

我已经在Ruby中编程了几个月了,我想知道什么时候使用常量而不是类变量,反之亦然.(我在Rails工作,考虑模型中的常量).

class Category
  TYPES = %w(listing event business).freeze
end
Run Code Online (Sandbox Code Playgroud)

要么

class Category
  @@types = %w(listing event business).freeze
  cattr_reader :types
end
Run Code Online (Sandbox Code Playgroud)

是否存在一种优于另一种情况的情况?或者只是品味/风格问题?

ruby constants class-variables

48
推荐指数
3
解决办法
2万
查看次数

我可以使用方法而不是常量吗?

使用常量而不是像这样返回这些常量的方法有什么意义吗?

class Foo
  LETTERS = [:a, :b, :c]
  # and them call it Foo::LETTERS
end

# or 
class Foo
  def self.letters
    [:a, :b, :c]
    # and then call it Foo.letters, more simplier
  end
end
Run Code Online (Sandbox Code Playgroud)

我只能看到第一种方法的一个优点:尝试重新定义常量时发出警告,但我认为这种情况很少见。

ruby

1
推荐指数
1
解决办法
68
查看次数

标签 统计

ruby ×2

class-variables ×1

constants ×1