Search code examples
ruby

Finding the first non-Nil element in an array


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


Solution

  • You can use Enumerable#find:

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