2

当然枚举在 Ruby 中不存在,但基于这篇文章,我使用了如下内容:

class PostType
   Page = 1,
   Post = 2
end

我想将值传递给一个方法并将其用于比较。所以:

initialize(post_type)
   if post_type = PostType::Page
       # do something here
   elsif post_type = PostType::Post
       # do something else here
   end
end

但这不起作用,无论我将什么传递给我的类的构造函数,它总是产生相同的结果。

关于为什么将“假枚举”传递给方法并尝试比较它不起作用的任何想法?我必须比较价值吗?即post_type = 2

4

5 回答 5

4

你分配而不是比较

initialize(post_type) 
   if post_type == PostType::Page 
       # do something here 
   elsif post_type == PostType::Post 
       # do something else here 
   end 
end 
于 2012-04-23T13:21:50.620 回答
4

除了你应该使用Symbols 的事实之外,还有一个语法错误,我假设你想要不同的语义:

if post_type = PostType::Page

应该

if post_type == PostType::Page

所以你的代码应该看起来像

if post_type == :page
...
于 2012-04-23T13:22:05.703 回答
4

您是在分配而不是比较。使用==而不是=应该产生更好的结果。

 initialize(post_type)
    if post_type == PostType::Page
        # do something here
    elsif post_type == PostType::Post
        # do something else here
    end
end
于 2012-04-23T13:22:13.770 回答
3

您可以使用case

case post_type
  when PostType::Page then  # Do something
  when PostType::Post then  # Do something else
  else raise 'Invalid post type'
end

此外,您确实应该Symbol为此使用 s :

case post_type
  when :page then # Do something
  when :post then # Do something else
  else raise 'Invalid post type'
end
于 2012-04-23T14:29:25.790 回答
1

这就是为什么这样做的好习惯:

def initialize(post_type)
   if PostType::Page == post_type
       # do something here
   elsif PostType::Post == post_type
       # do something else here
   end
end

如果你确实犯了这样的错误,编译器会发出警告"already initialized constant ..."

于 2012-04-23T13:37:57.560 回答