Ruby: Is There an Opposite of Include? for Ruby Arrays

Ruby: Is there an opposite of include? for Ruby Arrays?

if @players.exclude?(p.name)
...
end

ActiveSupport adds the exclude? method to Array, Hash, and String. This is not pure Ruby, but is used by a LOT of rubyists.

Source: Active Support Core Extensions (Rails Guides)

analogue for ActiveRecords' where for plain Ruby's arrays

There is findand selectin ruby (for one or multiple results, respectively).

selected = array.select do |item|
item[:attr1] == 'something'
end

select will pass each element of array to the block and pick those where the block returns a truthy value.
find is similar but it will return the first element where the block returns a truthy value.

Is there an opposite function of slice function in Ruby?

Use except:

a = {"foo" => 0, "bar" => 42, "baz" => 1024 }
a.except("foo")
# returns => {"bar" => 42, "baz" => 1024}

Ruby on Rails array .include? only check for reference and not object content?

Per the ruby 2.7 docs:

include?(object) → true or false

Returns true if the given object is present in self (that is, if any element == object), otherwise returns false.

If your DTO doesn't implement the equality operator == then it will use Object#== which only compares the object reference.

To add the operator to your class:

def ==(object)
# handle different type
return false unless object.is_a?(Soda::DTO::Bubble)

# compare internal variables etc.
object.container_id == self.container_id
end

How to check if a value exists in an array in Ruby

You're looking for include?:

>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true

Is there an opposite of String.next?

If your case is limited to unique character the following will allow you to get the previous
or next character:

def next_char(c)
(c.chr.ord + 1).chr
end

def prev_char(c)
(c.chr.ord - 1). chr
end

puts next_char('A')
puts prev_char('B')

However, as you deal with grades, I'd go for a kind a Enumeration of grade. For instance, take a look at that blog post for possible implementation.

Ref:

  • String.chr
  • String.ord
  • Integer.chr

Ruby refactor include? that takes in multiple strings

One way to do this would be

( (@taxon.tag || []) & ["shirts", "dibs"] ).present?

This might be helpful.

Let me try to explain the solution:

# @taxon.tag looks like an enumerable, but it could also be nil as you check it with
# .present? So to be safe, we do the following
(@taxon.tag || [])
# will guarentee to return an enumerable

# The & does an intersection of two arrays
# [1,2,3] & [3,4,5] will return 3
(@taxon.tag || []) & ["shirts, "dibs"]
# will return the common value, so if shirts and dibs are empty, will return empty

( (@taxon.tag || []) & ["shirts, "dibs"] ).present?
# should do what you set out to do


Related Topics



Leave a reply



Submit