Kieran Senior
Kieran Senior

Reputation: 18220

Ruby "Enum" Comparison

Of course enum's don't exist in Ruby, but based on this post I've used something like the following:

class PostType
   Page = 1,
   Post = 2
end

I want to pass the value to a method and use it for a comparison. So:

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

But this doesn't work, regardless of what I pass into the constructor of my class, it always yields the same result.

Any ideas as to why passing the "fake enum" into a method and trying to compare it won't work? Do I have to compare the value? i.e. post_type = 2 ?

Upvotes: 2

Views: 2377

Answers (5)

megas
megas

Reputation: 21791

That's why a good habit to do this:

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

If you do make such a mistake, the compiler will make a warning "already initialized constant ..."

Upvotes: 1

Matheus Moreira
Matheus Moreira

Reputation: 17020

You could use a case:

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

Also, you really should be using Symbols for this:

case post_type
  when :page then # Do something
  when :post then # Do something else
  else raise 'Invalid post type'
end

Upvotes: 3

Romain
Romain

Reputation: 12809

You're assigning instead of comparing. Using == instead of = should yield better results.

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

Upvotes: 4

Reactormonk
Reactormonk

Reputation: 21690

Besides the fact you should use Symbols, there's a syntax error, I assume you want different semantics:

if post_type = PostType::Page

should be

if post_type == PostType::Page

So your code should look like

if post_type == :page
...

Upvotes: 4

peter
peter

Reputation: 42182

you assign instead of compare

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

Upvotes: 4

Related Questions