Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything in ruby like object.in(array)? [duplicate]

Tags:

arrays

ruby

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)
like image 743
Andrew Avatar asked Jan 27 '23 02:01

Andrew


2 Answers

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'
like image 138
mrzasa Avatar answered Jan 29 '23 10:01

mrzasa


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
like image 41
SteveTurczyn Avatar answered Jan 29 '23 09:01

SteveTurczyn