Ruby - 相同类类型的常量

时间:2013-02-06 13:59:51

标签: ruby enums

我尝试了以下操作但是错误'错误的参数数量(2为0)':

class Rating
  NOOB = Rating.new(1, "U A NOOB")
  def initialize(rating, message)
    @rating = rating
    @message = message
  end
 end

相当于在Ruby中编写以下内容? (这是我做枚举的方式)

public class Rating {
  public static Rating NOOB = new Rating(1, "U SO NOOB");
  public static Rating EXPERT = new Rating(2, "U A PRO BRO");

  private int rating;
  private String message;

  public Rating(int rating, String message) {
    this.rating = rating;
    this.message = message;
  }
  ...
}

2 个答案:

答案 0 :(得分:1)

如果你放

就可以了
NOOB = Rating.new(1, "U A NOOB")

低于initialize的定义,否则解释器还没有解释它,并且不知道它所采用的参数。

答案 1 :(得分:0)

由于某种原因,如果你将常量声明放在initialize块的末尾,它就可以工作:

class Rating
  def initialize(rating, message)
    @rating = rating
    @message = message
  end
  NOOB = new(1, "U A NOOB")
end

p Rating::NOOB
=> #<Rating:0x0000000162a9c0 @rating=1, @message="U A NOOB">