Ruby Array find_first object? - ruby

Am I missing something in the Array documentation? I have an array which contains up to one object satisfying a certain criterion. I'd like to efficiently find that object. The best idea I have from the docs is this:
candidates = my_array.select { |e| e.satisfies_condition? }
found_it = candidates.first if !candidates.empty?
But I am unsatisfied for two reasons:
That select made me traverse the whole array, even though we could have bailed after the first hit.
I needed a line of code (with a condition) to flatten the candidates.
Both operations are wasteful with foreknowledge that there's 0 or 1 satisfying objects.
What I'd like is something like:
array.find_first(block)
which returns nil or the first object for which the block evaluates to true, ending the traversal at that object.
Must I write this myself? All those other great methods in Array make me think it's there and I'm just not seeing it.

Either I don't understand your question, or Enumerable#find is the thing you were looking for.

use array detect method if you wanted to return first value where block returns true
[1,2,3,11,34].detect(&:even?) #=> 2
OR
[1,2,3,11,34].detect{|i| i.even?} #=> 2
If you wanted to return all values where block returns true then use select
[1,2,3,11,34].select(&:even?) #=> [2, 34]

Guess you just missed the find method in the docs:
my_array.find {|e| e.satisfies_condition? }

Do you need the object itself or do you just need to know if there is an object that satisfies.
If the former then yes: use find:
found_object = my_array.find { |e| e.satisfies_condition? }
otherwise you can use any?
found_it = my_array.any? { |e| e.satisfies_condition? }
The latter will bail with "true" when it finds one that satisfies the condition.
The former will do the same, but return the object.

Related

What is the real use case for .Any() on arrays?

It clearly seems like I miss something very known and common but I can’t get why empty .Any() invocation on array and list differs in result.
As I know when I call .Any() it’s semantically equals of asking: "Does this box contain any items?". So when I write something like this:
List<int> list= new List<int>();
WriteLine(list.Any());//returns false
list.Add(1);
WriteLine(list.Any());//returns true
It expectedly returns false in the first case because list was empty and true when the item was added.
But further if I’ll try to use array instead and this array will be just initialized but empty (without any items) . Any() call will return true:
int[] arr = new int[2];
WriteLine(arr.Any());//returns true despite in has no items
So what’s the point to call empty .Any() on array to check if it has any items inside if it will always return true? Should I avoid use .Any() for such kind of purpose?
What’s the real use case of empty .Any call on array?
When you create an array, all elements are initialized with default values.
So, int[] arr = new int[2] is actually equal to int[] arr = new int[2] { 0, 0 }. That's why .Any() returns true.
Based on your code example, there is no meaningful use case for Any() method on an initialized array.
But, as I mentioned in the comment to your question, if you are calling a method which returns an array, then you can perform an Any() check on the returned array to determine, if it has got any elements.

Ruby: how to find the next match in an array

I have to search an item in an array and return the value of the next item. Example:
a = ['abc.df','-f','test.h']
i = a.find_index{|x| x=~/-f/}
puts a[i+1]
Is there any better way other than working with index?
A classical functional approach uses no indexes (xs.each_cons(2) -> pairwise combinations of xs):
xs = ['abc.df', '-f', 'test.h']
(xs.each_cons(2).detect { |x, y| x =~ /-f/ } || []).last
#=> "test.h"
Using Enumerable#map_detect simplifies it a litte bit more:
xs.each_cons(2).map_detect { |x, y| y if x =~ /-f/ }
#=> "test.h"
The reason something like array.find{something}.next doesn't exist is that it's an array rather than a linked list. Each item is just it's own value; it doesn't have a concept of "the item after me".
#tokland gives a good solution by iterating over the array with each pair of consecutive items, so that when the first item matches, you have your second item handy. There are strong arguments to be made for the functional style, to be sure. Your version is shorter, though, and I'd argue that yours is also more quickly and easily understood at a glance.
If the issue is that you're using it a lot and want something cleaner and more to the point, then of course you could just add it as a singleton method to a:
def a.find_after(&test)
self[find_index(&test).next]
end
Then
a.find_after{|x| x=~/-f/}
is a clear way to find the next item after the first match.
All of that said, I think #BenjaminCox makes the best point about what appears to be your actual goal. If you're parsing command line options, there are libraries that do that well.
I don't know of a cleaner way to do that specific operation. However, it sure looks like you're trying to parse command-line arguments. If so, I'd recommend using the built-in OptionParser module - it'll save a ton of time and hair-pulling trying to parse them yourself.
This article explains how it works.
Your solution working with indexes is fine, as others have commented. You could use Enumerable#drop_while to get an array from your match on and take the second element of that:
a = ['abc.df','-f','test.h']
f_arg = a.drop_while { |e| e !~ /-f/ }[1]

Changing one array in an array of arrays changes them all; why?

a = Array.new(3,[])
a[1][0] = 5
a => [[5], [5], [5]]
I thought this doesn't make sense!
isn't it should a => [[], [5], []]
or this's sort of Ruby's feature ?
Use this instead:
a = Array.new(3){ [] }
With your code the same object is used for the value of each entry; once you mutate one of the references you see all others change. With the above you instead invoke the block each time a new value is needed, which returns a new array each time.
This is similar in nature to the new user question about why the following does not work as expected:
str.gsub /(<([a-z]+)>/, "-->#{$1}<--"
In the above, string interpolation occurs before the gsub method is ever called, so it cannot use the then-current value of $1 in your string. Similarly, in your question you create an object and pass it to Array.new before Ruby starts creating array slots. Yes, the runtime could call dup on the item by default…but that would be potentially disastrous and slow. Hence you get the block form to determine on your own how to create the initial values.

How to recurse through arrays in Ruby

I'm trying to use the two following methods to recursively traverse arrays of arrays until the bottom and then come back up with the match results.
You know how in a tennis tournament they start with 32 matches and pair by pair the winner moves ahead, and at the end there's only one winner? That's what I want to replicate in Ruby.
I created a match_winner that always returns the first array for the sake of simplicity. Then, I send the whole tournament array into winner that calls itself recursively until it finds a simple array corresponding to a single match.
def match_winner(array_of_arrays)
return array_of_arrays[0]
end
def winner(tournament)
if tournament[0][0].is_a?(String)
return match_winner(tournament)
else
tournament.each{|e|
winner(e)
}
end
end
tournament = [
[["one", "two"],["three", "four"]],
[["five", "six"],["seven", "eight"]]
]
puts winner(tournament).inspect
Which outputs:
[[["one", "two"], ["three", "four"]], [["five", "six"], ["seven", "eight"]]]
I tried different permutations and variations on this algorithm but I couldn't make it work correctly and return only the final winner.
Does anyone see anything obviously wrong here?
Now I'm calling winner.
I know that the question looks like it's answered, but I just did the same problem and I have to say that simply changing each to map didn't work for me, because, as the code posted, the result is an array of the first-round winners. What worked for me is:
def winner(tournament)
if tournament[0][0].is_a?(String)
return match_winner(tournament)
else
tournament.map!{|e| #use map!, because we need to apply winner() to new values
e=winner(e) #assign new value somewhere, so recursion can climb back
}
end
end
Maybe more experienced developers can explain why that is. Without these two tips it won't work.
And yes, I know "bang" is a bad coding style, danger danger high voltage, but it's my second day with Ruby and I wanted to get this to work.
And, to understand recursion, you have to understand recursion.
Looks like you want map, not each, and, as a commenter above notes, you didn't call winner in the above code.
When you call:
tournament.each {...}
that method actually returns the tournament, which is thus what winner returns.
What you want is to replace it with
tournament.map {...}
which returns a new array consisting of calling "winner" on each element of tournament.
Assuming you have 2^n number of games always and match_winner works ok:
def winner(game)
if game[0][0][0] == game[0][0][0][0]
match_winner( [ game[0], game[1] ] )
else
match_winner( [winner(game[0]), winner(game[1])] )
end
end

Having a hard time understanding & implementing some Ruby code

myitem.inject({}) {|a,b| a[b.one] = b.two; a}
Where:
myitem is a class which holds an array or pair objects (pair objects have two fields in them one and two)
I am not sure what the above code is supposed to do?
Starting with an empty map, set its value for the b.one key to b.two.
In other words, for every item in the "myitem" collection, create a map entry. The key will be an item's "one" value. That map entry's value will be the item's "two" value.
The block given to "inject" receives two parameters. The first is the "accumulator". It's initial value in this case is the empty map passed to "inject". The second parameter is the current item in the collection. In this case, each item in the collection.
The block must return whatever will be used as the next accumulator value, in this case, the map. We want to keep using the same map, so when we're done, the "inject" method will return the map with all the key/value pairs.
Without saving the results of the inject it's a bit worthless.
It's a pedantic way of writing
h = {}
myitem.each { |b| h[b.one] = b.two }
or to be closer to your original code
a = {}
mytem.each { |b| a[b.one] = b.two }
(I personnaly hate this pattern (and people who use it) as it needs the ; a at the end, losing all the functional aspect of inject. (Using a side-effect function inside a 'functional pattern', and then realizing that the later function (a[..]) doesn't return the expecting object is just wrong, IMO).
Inject is normal use to 'fold' a list into a result like
[1,2,3].inject(0) { |sum, x| sum+x }
=> 6 # (0+1+2+3)
here sum is the result of the last call to the block, x is each value on the list and 0 is the initial value of sum.
[2,3].inject(10) { |p,x| p*x }
=> 60 # 10*2*3
etc ...
Hash[my_item.map {|object| [object.one, object.two]}]
is another way to do it.

Resources