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

I have a value 'Dog' and an array ['Cat', 'Dog', 'Bird'].
How do I check if it exists in the array without looping through it? Is there a simple way of checking if the value exists, nothing more?

You're looking for include?:
>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true

There is an in? method in ActiveSupport (part of Rails) since v3.1, as pointed out by #campeterson. So within Rails, or if you require 'active_support', you can write:
'Unicorn'.in?(['Cat', 'Dog', 'Bird']) # => false
OTOH, there is no in operator or #in? method in Ruby itself, even though it has been proposed before, in particular by Yusuke Endoh a top notch member of ruby-core.
As pointed out by others, the reverse method include? exists, for all Enumerables including Array, Hash, Set, Range:
['Cat', 'Dog', 'Bird'].include?('Unicorn') # => false
Note that if you have many values in your array, they will all be checked one after the other (i.e. O(n)), while that lookup for a hash will be constant time (i.e O(1)). So if you array is constant, for example, it is a good idea to use a Set instead. E.g:
require 'set'
ALLOWED_METHODS = Set[:to_s, :to_i, :upcase, :downcase
# etc
]
def foo(what)
raise "Not allowed" unless ALLOWED_METHODS.include?(what.to_sym)
bar.send(what)
end
A quick test reveals that calling include? on a 10 element Set is about 3.5x faster than calling it on the equivalent Array (if the element is not found).
A final closing note: be wary when using include? on a Range, there are subtleties, so refer to the doc and compare with cover?...

Try
['Cat', 'Dog', 'Bird'].include?('Dog')

If you want to check by a block, you could try any? or all?.
%w{ant bear cat}.any? {|word| word.length >= 3} #=> true
%w{ant bear cat}.any? {|word| word.length >= 4} #=> true
[ nil, true, 99 ].any? #=> true
See Enumerable for more information.
My inspiration came from "evaluate if array has any items in ruby"

Use Enumerable#include:
a = %w/Cat Dog Bird/
a.include? 'Dog'
Or, if a number of tests are done,1 you can get rid of the loop (that even include? has) and go from O(n) to O(1) with:
h = Hash[[a, a].transpose]
h['Dog']
1. I hope this is obvious but to head off objections: yes, for just a few lookups, the Hash[] and transpose ops dominate the profile and are each O(n) themselves.

Ruby has eleven methods to find elements in an array.
The preferred one is include? or, for repeated access, creat a Set and then call include? or member?.
Here are all of them:
array.include?(element) # preferred method
array.member?(element)
array.to_set.include?(element)
array.to_set.member?(element)
array.index(element) > 0
array.find_index(element) > 0
array.index { |each| each == element } > 0
array.find_index { |each| each == element } > 0
array.any? { |each| each == element }
array.find { |each| each == element } != nil
array.detect { |each| each == element } != nil
They all return a trueish value if the element is present.
include? is the preferred method. It uses a C-language for loop internally that breaks when an element matches the internal rb_equal_opt/rb_equal functions. It cannot get much more efficient unless you create a Set for repeated membership checks.
VALUE
rb_ary_includes(VALUE ary, VALUE item)
{
long i;
VALUE e;
for (i=0; i<RARRAY_LEN(ary); i++) {
e = RARRAY_AREF(ary, i);
switch (rb_equal_opt(e, item)) {
case Qundef:
if (rb_equal(e, item)) return Qtrue;
break;
case Qtrue:
return Qtrue;
}
}
return Qfalse;
}
member? is not redefined in the Array class and uses an unoptimized implementation from the Enumerable module that literally enumerates through all elements:
static VALUE
member_i(RB_BLOCK_CALL_FUNC_ARGLIST(iter, args))
{
struct MEMO *memo = MEMO_CAST(args);
if (rb_equal(rb_enum_values_pack(argc, argv), memo->v1)) {
MEMO_V2_SET(memo, Qtrue);
rb_iter_break();
}
return Qnil;
}
static VALUE
enum_member(VALUE obj, VALUE val)
{
struct MEMO *memo = MEMO_NEW(val, Qfalse, 0);
rb_block_call(obj, id_each, 0, 0, member_i, (VALUE)memo);
return memo->v2;
}
Translated to Ruby code this does about the following:
def member?(value)
memo = [value, false, 0]
each_with_object(memo) do |each, memo|
if each == memo[0]
memo[1] = true
break
end
memo[1]
end
Both include? and member? have O(n) time complexity since the both search the array for the first occurrence of the expected value.
We can use a Set to get O(1) access time at the cost of having to create a Hash representation of the array first. If you repeatedly check membership on the same array this initial investment can pay off quickly. Set is not implemented in C but as plain Ruby class, still the O(1) access time of the underlying #hash makes this worthwhile.
Here is the implementation of the Set class:
module Enumerable
def to_set(klass = Set, *args, &block)
klass.new(self, *args, &block)
end
end
class Set
def initialize(enum = nil, &block) # :yields: o
#hash ||= Hash.new
enum.nil? and return
if block
do_with_enum(enum) { |o| add(block[o]) }
else
merge(enum)
end
end
def merge(enum)
if enum.instance_of?(self.class)
#hash.update(enum.instance_variable_get(:#hash))
else
do_with_enum(enum) { |o| add(o) }
end
self
end
def add(o)
#hash[o] = true
self
end
def include?(o)
#hash.include?(o)
end
alias member? include?
...
end
As you can see the Set class just creates an internal #hash instance, maps all objects to true and then checks membership using Hash#include? which is implemented with O(1) access time in the Hash class.
I won't discuss the other seven methods as they are all less efficient.
There are actually even more methods with O(n) complexity beyond the 11 listed above, but I decided to not list them since they scan the entire array rather than breaking at the first match.
Don't use these:
# bad examples
array.grep(element).any?
array.select { |each| each == element }.size > 0
...

Several answers suggest Array#include?, but there is one important caveat: Looking at the source, even Array#include? does perform looping:
rb_ary_includes(VALUE ary, VALUE item)
{
long i;
for (i=0; i<RARRAY_LEN(ary); i++) {
if (rb_equal(RARRAY_AREF(ary, i), item)) {
return Qtrue;
}
}
return Qfalse;
}
The way to test the word presence without looping is by constructing a trie for your array. There are many trie implementations out there (google "ruby trie"). I will use rambling-trie in this example:
a = %w/cat dog bird/
require 'rambling-trie' # if necessary, gem install rambling-trie
trie = Rambling::Trie.create { |trie| a.each do |e| trie << e end }
And now we are ready to test the presence of various words in your array without looping over it, in O(log n) time, with same syntactic simplicity as Array#include?, using sublinear Trie#include?:
trie.include? 'bird' #=> true
trie.include? 'duck' #=> false

If you don't want to loop, there's no way to do it with Arrays. You should use a Set instead.
require 'set'
s = Set.new
100.times{|i| s << "foo#{i}"}
s.include?("foo99")
=> true
[1,2,3,4,5,6,7,8].to_set.include?(4)
=> true
Sets work internally like Hashes, so Ruby doesn't need to loop through the collection to find items, since as the name implies, it generates hashes of the keys and creates a memory map so that each hash points to a certain point in memory. The previous example done with a Hash:
fake_array = {}
100.times{|i| fake_array["foo#{i}"] = 1}
fake_array.has_key?("foo99")
=> true
The downside is that Sets and Hash keys can only include unique items and if you add a lot of items, Ruby will have to rehash the whole thing after certain number of items to build a new map that suits a larger keyspace. For more about this, I recommend you watch "MountainWest RubyConf 2014 - Big O in a Homemade Hash by Nathan Long".
Here's a benchmark:
require 'benchmark'
require 'set'
array = []
set = Set.new
10_000.times do |i|
array << "foo#{i}"
set << "foo#{i}"
end
Benchmark.bm do |x|
x.report("array") { 10_000.times { array.include?("foo9999") } }
x.report("set ") { 10_000.times { set.include?("foo9999") } }
end
And the results:
user system total real
array 7.020000 0.000000 7.020000 ( 7.031525)
set 0.010000 0.000000 0.010000 ( 0.004816)

This is another way to do this: use the Array#index method.
It returns the index of the first occurrence of the element in the array.
For example:
a = ['cat','dog','horse']
if a.index('dog')
puts "dog exists in the array"
end
index() can also take a block:
For example:
a = ['cat','dog','horse']
puts a.index {|x| x.match /o/}
This returns the index of the first word in the array that contains the letter 'o'.

Fun fact,
You can use * to check array membership in a case expressions.
case element
when *array
...
else
...
end
Notice the little * in the when clause, this checks for membership in the array.
All the usual magic behavior of the splat operator applies, so for example if array is not actually an array but a single element it will match that element.

Check exists
Use include?
Example:
arr = [1, 2, 3]
arr.include?(1) -> true
arr.include?(4) -> false
Check does not exist
Use exclude?
Example:
arr = %w(vietnam china japan)
arr.exclude?('usa') -> true
arr.exclude?('china') -> false

There are multiple ways to accomplish this. A few of them are as follows:
a = [1,2,3,4,5]
2.in? a #=> true
8.in? a #=> false
a.member? 1 #=> true
a.member? 8 #=> false

This will tell you not only that it exists but also how many times it appears:
a = ['Cat', 'Dog', 'Bird']
a.count("Dog")
#=> 1

You can try:
Example: if Cat and Dog exist in the array:
(['Cat','Dog','Bird'] & ['Cat','Dog'] ).size == 2 #or replace 2 with ['Cat','Dog].size
Instead of:
['Cat','Dog','Bird'].member?('Cat') and ['Cat','Dog','Bird'].include?('Dog')
Note: member? and include? are the same.
This can do the work in one line!

If you need to check multiples times for any key, convert arr to hash, and now check in O(1)
arr = ['Cat', 'Dog', 'Bird']
hash = arr.map {|x| [x,true]}.to_h
=> {"Cat"=>true, "Dog"=>true, "Bird"=>true}
hash["Dog"]
=> true
hash["Insect"]
=> false
Performance of Hash#has_key? versus Array#include?
Parameter Hash#has_key? Array#include
Time Complexity O(1) operation O(n) operation
Access Type Accesses Hash[key] if it Iterates through each element
returns any value then of the array till it
true is returned to the finds the value in Array
Hash#has_key? call
call
For single time check using include? is fine

For what it's worth, The Ruby docs are an amazing resource for these kinds of questions.
I would also take note of the length of the array you're searching through. The include? method will run a linear search with O(n) complexity which can get pretty ugly depending on the size of the array.
If you're working with a large (sorted) array, I would consider writing a binary search algorithm which shouldn't be too difficult and has a worst case of O(log n).
Or if you're using Ruby 2.0, you can take advantage of bsearch.

If we want to not use include? this also works:
['cat','dog','horse'].select{ |x| x == 'dog' }.any?

How about this way?
['Cat', 'Dog', 'Bird'].index('Dog')

['Cat', 'Dog', 'Bird'].detect { |x| x == 'Dog'}
=> "Dog"
!['Cat', 'Dog', 'Bird'].detect { |x| x == 'Dog'}.nil?
=> true

If you're trying to do this in a MiniTest unit test, you can use assert_includes. Example:
pets = ['Cat', 'Dog', 'Bird']
assert_includes(pets, 'Dog') # -> passes
assert_includes(pets, 'Zebra') # -> fails

There's the other way around this.
Suppose the array is [ :edit, :update, :create, :show ], well perhaps the entire seven deadly/restful sins.
And further toy with the idea of pulling a valid action from some string:
"my brother would like me to update his profile"
Then:
[ :edit, :update, :create, :show ].select{|v| v if "my brother would like me to update his profile".downcase =~ /[,|.| |]#{v.to_s}[,|.| |]/}

I always find it interesting to run some benchmarks to see the relative speed of the various ways of doing something.
Finding an array element at the start, middle or end will affect any linear searches but barely affect a search against a Set.
Converting an Array to a Set is going to cause a hit in processing time, so create the Set from an Array once, or start with a Set from the very beginning.
Here's the benchmark code:
# frozen_string_literal: true
require 'fruity'
require 'set'
ARRAY = (1..20_000).to_a
SET = ARRAY.to_set
DIVIDER = '-' * 20
def array_include?(elem)
ARRAY.include?(elem)
end
def array_member?(elem)
ARRAY.member?(elem)
end
def array_index(elem)
ARRAY.index(elem) >= 0
end
def array_find_index(elem)
ARRAY.find_index(elem) >= 0
end
def array_index_each(elem)
ARRAY.index { |each| each == elem } >= 0
end
def array_find_index_each(elem)
ARRAY.find_index { |each| each == elem } >= 0
end
def array_any_each(elem)
ARRAY.any? { |each| each == elem }
end
def array_find_each(elem)
ARRAY.find { |each| each == elem } != nil
end
def array_detect_each(elem)
ARRAY.detect { |each| each == elem } != nil
end
def set_include?(elem)
SET.include?(elem)
end
def set_member?(elem)
SET.member?(elem)
end
puts format('Ruby v.%s', RUBY_VERSION)
{
'First' => ARRAY.first,
'Middle' => (ARRAY.size / 2).to_i,
'Last' => ARRAY.last
}.each do |k, element|
puts DIVIDER, k, DIVIDER
compare do
_array_include? { array_include?(element) }
_array_member? { array_member?(element) }
_array_index { array_index(element) }
_array_find_index { array_find_index(element) }
_array_index_each { array_index_each(element) }
_array_find_index_each { array_find_index_each(element) }
_array_any_each { array_any_each(element) }
_array_find_each { array_find_each(element) }
_array_detect_each { array_detect_each(element) }
end
end
puts '', DIVIDER, 'Sets vs. Array.include?', DIVIDER
{
'First' => ARRAY.first,
'Middle' => (ARRAY.size / 2).to_i,
'Last' => ARRAY.last
}.each do |k, element|
puts DIVIDER, k, DIVIDER
compare do
_array_include? { array_include?(element) }
_set_include? { set_include?(element) }
_set_member? { set_member?(element) }
end
end
Which, when run on my Mac OS laptop, results in:
Ruby v.2.7.0
--------------------
First
--------------------
Running each test 65536 times. Test will take about 5 seconds.
_array_include? is similar to _array_index
_array_index is similar to _array_find_index
_array_find_index is faster than _array_any_each by 2x ± 1.0
_array_any_each is similar to _array_index_each
_array_index_each is similar to _array_find_index_each
_array_find_index_each is faster than _array_member? by 4x ± 1.0
_array_member? is faster than _array_detect_each by 2x ± 1.0
_array_detect_each is similar to _array_find_each
--------------------
Middle
--------------------
Running each test 32 times. Test will take about 2 seconds.
_array_include? is similar to _array_find_index
_array_find_index is similar to _array_index
_array_index is faster than _array_member? by 2x ± 0.1
_array_member? is faster than _array_index_each by 2x ± 0.1
_array_index_each is similar to _array_find_index_each
_array_find_index_each is similar to _array_any_each
_array_any_each is faster than _array_detect_each by 30.000000000000004% ± 10.0%
_array_detect_each is similar to _array_find_each
--------------------
Last
--------------------
Running each test 16 times. Test will take about 2 seconds.
_array_include? is faster than _array_find_index by 10.000000000000009% ± 10.0%
_array_find_index is similar to _array_index
_array_index is faster than _array_member? by 3x ± 0.1
_array_member? is faster than _array_find_index_each by 2x ± 0.1
_array_find_index_each is similar to _array_index_each
_array_index_each is similar to _array_any_each
_array_any_each is faster than _array_detect_each by 30.000000000000004% ± 10.0%
_array_detect_each is similar to _array_find_each
--------------------
Sets vs. Array.include?
--------------------
--------------------
First
--------------------
Running each test 65536 times. Test will take about 1 second.
_array_include? is similar to _set_include?
_set_include? is similar to _set_member?
--------------------
Middle
--------------------
Running each test 65536 times. Test will take about 2 minutes.
_set_member? is similar to _set_include?
_set_include? is faster than _array_include? by 1400x ± 1000.0
--------------------
Last
--------------------
Running each test 65536 times. Test will take about 4 minutes.
_set_member? is similar to _set_include?
_set_include? is faster than _array_include? by 3000x ± 1000.0
Basically the results tell me to use a Set for everything if I'm going to search for inclusion unless I can guarantee that the first element is the one I want, which isn't very likely. There's some overhead when inserting elements into a hash, but the search times are so much faster I don't think that should ever be a consideration. Again, if you need to search it, don't use an Array, use a Set. (Or a Hash.)
The smaller the Array, the faster the Array methods will run, but they're still not going to keep up, though in small arrays the difference might be tiny.
"First", "Middle" and "Last" reflect the use of first, size / 2 and last for ARRAY for the element being searched for. That element will be used when searching the ARRAY and SET variables.
Minor changes were made for the methods that were comparing to > 0 because the test should be >= 0 for index type tests.
More information about Fruity and its methodology is available in its README.

it has many ways to find a element in any array but the simplest way is 'in ?' method.
example:
arr = [1,2,3,4]
number = 1
puts "yes #{number} is present in arr" if number.in? arr

If you want to return the value not just true or false, use
array.find{|x| x == 'Dog'}
This will return 'Dog' if it exists in the list, otherwise nil.

if you don't want to use include? you can first wrap the element in an array and then check whether the wrapped element is equal to the intersection of the array and the wrapped element. This will return a boolean value based on equality.
def in_array?(array, item)
item = [item] unless item.is_a?(Array)
item == array & item
end

Here is one more way to do this:
arr = ['Cat', 'Dog', 'Bird']
e = 'Dog'
present = arr.size != (arr - [e]).size

array = [ 'Cat', 'Dog', 'Bird' ]
array.include?("Dog")

Try below
(['Cat', 'Dog', 'Bird'] & ['Dog']).any?

Related

Each loop inside Case for Ruby

I'm trying to dynamically generate a case statement based on an array of values. For example let's say I have an array of ranges
[1..3,4..6,7..20,21..38]
and I want to write a dynamic case statement that returns the first number of whatever range
case n
ranges.each do |r|
when r
r.first
end
end
Is this possible, or will I have to find another way to do it (my actual code is more complex)?
If i get your question right, then you can forget case statement and do it using detect:
ary = [1..3, 4..6, 7..20, 21..38]
num = 15 # say
ary.detect { |sub_ary| sub_ary.include?(num) }
=> 7..20
ary.detect { |sub_ary| sub_ary.include?(num) }.first # call `first` on result of above, which is a range, to get the first element.
=> 7
Just out of curiosity:
number = 5
instance_eval [
"case number",
*ranges.map { |r| "when #{r} then (#{r}).first" },
"end"
].join($/)
#⇒ 4
In addition to #detect (or #find) with #include? from Jagdeep Singhs answer you can also use the case equality operator (Range#===). This operator is used by the case statement to compare the input value with the scenario's you're providing.
ranges.find { |range| range === n }.first
Keep in mind both #detect and #find return nil if no value can be found. This means you might want to use the safe navigation operator (}&.first) to prevent a no method exception of #first on nil if the value can't be found.
Well, this works, but is kind of pointless and thread unsafe:
def get_range(n)
ranges = [1..3,4..6,7..20,21..38]
case n
when 3
# special case
199
when ->(x) { #_get_range = ranges.find { |r| r.cover?(x) } }
#_get_range.first
else
0
end
ensure
remove_instance_variable(:#_get_range) if instance_variable_defined?(:#_get_range)
end
get_range(3) # => 199
get_range(5) # => 4
get_range(50) # => 0
You could just do:
ranges.find { |r| r.cover?(n) }&.first || 0
My two cents..
ranges = [1..3,4..6,7..20,21..38]
num = 15
ranges.bsearch { |range| range.member? num }.begin

Why Range#include? is much slower than greater or less than operator

I have a array of hashes which key are Date and value are Integer.
This is a test code to emulate it.
hashes = 2000.times.map do |i|
[Date.new(2017) - i.days, rand(100)]
end.to_h
I want to get values of a specific period.
At first I wrote with Range#include?, but it was quite slow.
Benchmark.measure do
hashes.select{|k,v| (Date.new(2012,3,3)..Date.new(2012,6,10)).include?(k)}
end
#<Benchmark::Tms:0x007fd16479bed0 #label="", #real=2.9242447479628026, #cstime=0.0, #cutime=0.0, #stime=0.0, #utime=2.920000000000016, #total=2.920000000000016>
With simple greater or less than operator it became 60 times faster.
Benchmark.measure do
hashes.select{|k,v| k >= Date.new(2012,3,3) && k <= Date.new(2012,6,10)}
end
#<Benchmark::Tms:0x007fd162b61670 #label="", #real=0.05436371313408017, #cstime=0.0, #cutime=0.0, #stime=0.0, #utime=0.05000000000001137, #total=0.05000000000001137>
I thought these two expression are basically same.
Why there is so big difference?
You need to use Range#cover? instead of Range#include?, and to calculate the range just once, not once for each element of measure. cover? compares the block variable k with the end-points of the range; include? (for non-numeric objects, such as dates) compares each element in the range with the block variable until it finds a match or concludes there is no match (similar to Array#include?).
In addition, you wish to consider the first and only key of each element of hashes (a hash), so if that hash is h, the first key-value pair is h.first, and the key of that pair is h.first.first.
require 'date'
Benchmark.measure do
r = Date.new(2012,3,3)..Date.new(2012,6,10)
hashes.select{|h| r.cover? h.first.first }
end
This should be nearly identical to your second method in terms of execution speed.
An example
hashes = [{ Date.new(2012,3,1)=>1 }, { Date.new(2012,4,20)=>2 },
{ Date.new(2012,6,10)=>3 }, { Date.new(2012,6,11)=>4 }]
#=> [{#<Date: 2012-03-01 ((2455988j,0s,0n),+0s,2299161j)>=>1},
# {#<Date: 2012-04-20 ((2456038j,0s,0n),+0s,2299161j)>=>2},
# {#<Date: 2012-06-10 ((2456089j,0s,0n),+0s,2299161j)>=>3},
# {#<Date: 2012-06-11 ((2456090j,0s,0n),+0s,2299161j)>=>4}]
r = Date.new(2012,3,3)..Date.new(2012,6,10)
hashes.select{|h| r.cover? h.first.first }
#=> {#<Date: 2012-04-20 ((2456038j,0s,0n),+0s,2299161j)>=>2,
# #<Date: 2012-06-10 ((2456089j,0s,0n),+0s,2299161j)>=>3}

Compare two dimensional arrays

I have two two-dimensional arrays,
a = [[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"],
[17368, "I63.9"]]
and
b = [[17360, "I87.2"],
[17361, "s93.601"],
[17362, "h66.91"],
[17363, "h25.12"],
[17364, "Z51.89"],
[17365, "z00.121"],
[17366, "z00.129"],
[17367, "k55.9"],
[17368, "I63.9"]]
I would like to count similar rows in both the arrays irrespective of the character case, i.e., "h25.12" would be equal to "H25.12".
I tried,
count = a.count - (a - b).count
But (a - b) returns
[[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"]]
I need the count as 5 since there are five similar rows when we do not consider the character case.
Instead of a - b you should do this:
a.map{|k,v| [k,v.downcase]} - b.map{|k,v| [k,v.downcase]} # case-insensitive
You can convert Arrays to Hash, and use Enumerable#count with a block.
b_hash = b.to_h
a.to_h.count {|k, v| b_hash[k] && b_hash[k].downcase == v.downcase }
# => 5
It will convert second element of inner array to upcase for both array then you can perform subtraction, then It will return exact result that you want
a.map{|first,second| [first,second.upcase]} - b.map{|first,second| [first,second.upcase]}
You can zip them and then use the block form of count:
a.zip(b).count{|e| e[0][1].downcase == e[1][1].downcase}
a.count - (a.map{|e| [e[0],e[1].downcase] } - b.map{|e| [e[0],e[1].downcase] }).count
The above maps a and b to new arrays where the second sub-array element is downcase.
You want to count similar, so &(AND) operation is more suitable.
(a.map { |k, v| [k, v.upcase] } & b.map { |k, v| [k, v.upcase] }).count
Using Proc and '&':
procedure = Proc.new { |i, j| [i, j.upcase] }
(a.map(&procedure) & b.map(&procedure)).count
#=> 5
For better understanding, let's simplify it:
new_a = a.map {|i, j| [i, j.upcase]}
new_b = b.map {|i, j| [i, j.upcase]}
# Set intersection using '&'
(new_a & new_b).count
#=> 5
I have assumed that the ith element of a is to be compared with the ith element of b. (Edit: a subsequent comment by the OP confirmed this interpretation.)
I would be inclined to use indices to avoid the construction of relatively large temporary arrays. Here are two ways that might be done.
#1 Use indices
[a.size,b.size].min.size.times.count do |i|
af,al=a[i]
bf,bl=b[i];
af==bf && al.downcase==bl.downcase
end
#=> 5
#2 Use Refinements
My purpose in giving this solution is to illustrate the use of Refinements. I would not argue for its use for the problem at hand, but this problem provides a good vehicle for showing how the technique can be applied.
I could not figure out how best to do this, so I posted this question on SO. I've applied #ZackAnderson's answer below.
module M
refine String do
alias :dbl_eql :==
def ==(other)
downcase.dbl_eql(other.downcase)
end
end
refine Array do
def ==(other)
zip(other).all? {|x, y| x == y}
end
end
end
'a' == 'A' #=> false (as expected)
[1,'a'] == [1,'A'] #=> false (as expected)
using M
'a' == 'A' #=> true
[1,'a'] == [1,'A'] #=> true
I could use Enumerable#zip, but for variety I'll use Object#to_enum and Kernel#loop in conjunction with Enumerator#next:
ea, eb = a.to_enum, b.to_enum
cnt = 0
loop do
cnt += 1 if ea.next == eb.next
end
cnt #=> 5

How to group anagrams together of a array in Ruby

I am trying to write a function called anagram() and return the following output:
Example = ['Creams', 'bart','bAtr', 'bar', 'rabt', 'Cars','creamsery', 'Scar', 'scream']
puts anagram(Example)
OUTPUT:
[["Creams", "scream"] ["bart", "bAtr", "rabt"], ["bar"], ["Cars","Scar"],["creamsery"]]
I know I can use:
Example[i].downcase.char.sort.join
to compare each element in the array, but I have a hard time grouping them all together inside a loop.
What about this:
def anagrams(ary)
h = Hash.new([])
ary.each.with_index { |el, i| h[el.downcase.chars.sort.join] += [i] }
h.map { |key, indexes| indexes.map { |i| ary[i] } }
end
The function saves the indexes in a hash and then returns the corresponding elements.
This approach scans the array at most twice, therefore it's O(n). Even if it is not particularly elegant, it is quite fast.
What about this:
def anagram(ary)
ary.map do |el|
ary.select{ |x| el.downcase.chars.sort.join('') == x.downcase.chars.sort.join('') }
end.uniq
end
Calling .chars on a String will provide you an Array of chars that you can sort and then .join back to a String.
You can try it on the console:
> ary = ['Creams', 'bart','bAtr', 'bar', 'rabt', 'Cars','creamsery', 'Scar', 'scream']
> anagram ary
=> [["Creams", "scream"], ["bart", "bAtr", "rabt"], ["bar"], ["Cars", "Scar"], ["creamsery"]]
Of course, this is not particularly elegant or efficient. I'm eager to learn from others.
Example.group_by{|w| w.downcase.chars.sort}.values
One liner -
array.inject({}){|hash, ele| key = ele.chars.sort.join.downcase; hash[key] = (hash[key] || []) + [ele]; hash }.values
Complexity - O(n * mlogm), where n => number of elements, m => max size of string length.
If value of m is negligible comparing to n then complexity will be O(n)

Adding array together with nil as a possibility

I am creating a method that will take an array of numbers and add them together. I don't want to use inject because I haven't learned it yet. I prefer to start with the basics. I want to use either each or while.
I've been re-writing this code and testing it against rspec, and I keep running into a problem because the first test consists of the array being empty with nil. I tried doing an if else statement to set nil to 0 if the array is empty?, but that didn't seem to work. Here is what I've got right now.
def sum(x)
total = 0
sum.each { |x| total += x}
total
end
The rspec is testing an empty array [] as well as others that have multiple integers. Thoughts?
You're not enumerating the array passed in to the method, you're enumerating the variable sum. You want x.each { |x| total += x}, although using x within the {} is a little odd in this case because you've used the name for your method parameter.
You can use compact! to remove the nils from your array.
def sum(x)
total = 0
x.compact! #lose the nils
x.each { |i| total += i}
total
end
Edit:
If the x being passed to your sum() method is nil, you can check for that with nil?.
The do something like
if x.nil?
0 #assuming you want to return 0
else
#rest of your function
You want to return nil if the array passed in is empty?
You are getting confused with your identifiers. You are trying to iterate over sum, which is the name of the method, and you are using x as both the method parameter and the iteration block parameter.
I suggest you use something more descriptive, like arr for the method parameter and v for the block parameter (holding the value of each value from the array).
Finally, you need to initialise the total to nil so that the correct value is returned if the array is empty. Unfortunately you can't do arithmetic on nil, so in the code below I have added a line to set total to zero if it isn't already set.
This will do what you ask.
def sum(arr)
total = nil
arr.each do |v|
total = 0 unless total
total += v
end
total
end
p sum [1,2,3]
p sum []
output
6
nil
You could create a new instance method for the Array class:
class Array
def sum
total = 0.0
self.each {|x| total += x if ['Fixnum', 'Float'].include?(x.class.name)}
total%1==0 ? total.to_i : total
end
end
Then you would use it like so:
puts [].sum # => 0
puts [1, 2, 3].sum # => 6
puts [2, nil, "text", 4.5].sum # => 6.5

Resources