Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby "Enum" Comparison

Tags:

ruby

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 ?

like image 420
Kezzer Avatar asked Jul 21 '26 18:07

Kezzer


1 Answers

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 
like image 119
peter Avatar answered Jul 23 '26 06:07

peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!