Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid iterating over a nil array in Ruby?

Tags:

ruby

I want avoid iterating over a nil array.

My bad solution:

if nil!=myArr
    myArr.each { |item|
      p item;
    }
 end
like image 312
Ben Avatar asked Mar 26 '12 14:03

Ben


People also ask

How do you get rid of nil in Ruby?

Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.

What is the simplest way to iterate through the items of an array Ruby?

The Ruby Enumerable#each method is the most simplistic and popular way to iterate individual items in an array. It accepts two arguments: the first being an enumerable list, and the second being a block. It takes each element in the provided list and executes the block, taking the current item as a parameter.

What does .each do in Ruby?

each is just another method on an object. That means that if you want to iterate over an array with each , you're calling the each method on that array object. It takes a list as it's first argument and a block as the second argument.

What does nil mean in Ruby?

In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void.


2 Answers

For a simple one-liner, you might also use unless myArr.nil?

myArr.each { |item| p item } unless myArr.nil?

Updating for Ruby >= 2.3.0:

If you are comfortable with a nil return rather than avoiding execution entirely, you can use the Safe navigation operator &.. Note though that this differs slightly. Whereas the unless version will skip execution entirely, the &. will execute but return nil.

myArr&.each { |item| p item }
# returns nil
like image 151
Michael Berkowski Avatar answered Oct 05 '22 10:10

Michael Berkowski


In ruby, only nil and false are considered as false.

if myArr
    myArr.each { |item|
      p item
    }
end
like image 22
xdazz Avatar answered Oct 05 '22 08:10

xdazz