2

我尝试了以下方法,但收到错误“参数数量错误(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;
  }
  ...
}
4

2 回答 2

1

如果你把它工作

NOOB = Rating.new(1, "U A NOOB")

在 的定义之下initialize,否则解释器还没有解释它,也不知道它需要的参数。

于 2013-02-06T14:13:43.720 回答
0

出于某种原因,如果将常量声明放在初始化块的末尾,它会起作用:

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">
于 2013-02-06T14:12:41.297 回答