check if array is empty in ruby

To check if an array is empty in Ruby, you can use the empty? method provided by the Array class. Here's an example:

main.rb
my_array = []

if my_array.empty?
  puts "The array is empty"
else
  puts "The array is not empty"
end
103 chars
8 lines

In this example, the empty? method is used to check if my_array is empty. If it is empty, the code inside the if block will be executed, printing "The array is empty" to the console. If the array is not empty, the code inside the else block will be executed, printing "The array is not empty".

Note that you can also use the length method to check the size of an array and determine if it is empty:

main.rb
my_array = []

if my_array.length == 0
  puts "The array is empty"
else
  puts "The array is not empty"
end
108 chars
8 lines

However, using empty? is generally considered more idiomatic Ruby.

gistlibby LogSnag