So the standard way to write this seems to be array.include?(object)
. However I find that much harder to read and understand quickly compared to object.in(array). Is there anything like this in ruby?
The example I just hit this again was (user_role is a string, and allowed_user_roles is an array of strings):
allowed_user_roles.include?(user_role)
I know its probably personal preference, but I find this so much easier to read and comprehend.
user_role.in(allowed_user_roles)
It's not in core Ruby, but it's added in ActiveSupport core extensions. If you use Rails, you have that available:
1.in?([1,2]) # => true
"lo".in?("hello") # => true
25.in?(30..50) # => false
1.in?(1) # => ArgumentError
To use it outside of Rails, you need to install active_support
gem and then require active_support/core_ext/object/inclusion
:
# Gemfile
gem 'active_support'
# code
require 'active_support/core_ext/object/inclusion'
As an experiement, you could also create this yourself (although monkeypatching is generally frowned on)
class Object
def in?(collection)
raise ArgumentError unless collection.respond_to?(:include?)
collection.include?(self)
end
end
Then anything inheriting from Object (which is pretty much anything) will have an #in?
method.
5.in?(0..10)
=> true
'carrot'.in?(['potato', 'carrot', 'lettuce'])
=> true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With