5

I have this code:

default_group_id =  @group_list[0].list[0].name

But sometimes the list member of @group_list[0] is empty so my code crashes :) So I need to find the first @group_list[i] that its list member is not nil and use that. How can we do this?

Here is the structure:

enter image description here

1
  • Just loop through the list. What's stopping you? Commented Aug 26, 2013 at 16:09

5 Answers 5

24

Enumerable#find with passed Object#itself is a handy shortcut:

@group_list.find(&:itself)
Sign up to request clarification or add additional context in comments.

5 Comments

this is witchcraft
Doesn't find falsey values though. Usually this is fine, but it's not strictly answering the question.
But how does this work?
@DenysAvilov itself method returns the object itself. find searches for the first element in an enumerable for which passed function returns truthy value, which means value that is not nil or false. &:itself is the same as { |obj| obj.itself }. So find searches for the first non-nil non-false value in the enumerable.
@kolen thanks for the explanation! I'm kinda new to Ruby and got stuck with this construct I saw in my colleague's code. I honestly doubt it's a good idea to use such magic shortcuts even though they seem neat and smart, as it might impact readability for others...
10

You can use Enumerable#find:

@group_list.find { |x| !x["list"].blank? }
#=> first non-nil and non-empty list in group_list

3 Comments

sorry didn't work, still the same issue. I updated my question with the structure I am accessing. Hopefully that clarifies more my question. Thanks.
Note that find{|x|x} will reject nil and false, although it doesn't pertain to this question.
Note also that Object#blank? is a Rails extension and is not part of the Ruby core language; again, not sure if this pertains to OP.
7

You could use Enumerable#find:

@group_list.find{|x|!x.nil?} # => the first non-nil element in @group_list

Comments

2

Alternatively:

@group_list.compact.first

Comments

1

Using modern Ruby syntax:

@group_list.find { !_1.nil? }

If you don't care about false values:

@group_list.find { _1 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.