简体   繁体   中英

Rails check if an array exists

Sorry for my probably noobish question; I recently started developing with Rails. I checked through the API, documentation, and did a bunch of searches but could not find what I was look for.

Is there a method to check to see if a specific array exists?

For example,

    array = []
    array = [2,3,4]
    if array.exists?
      puts "array exists!"
    else
      puts "No such thing!"
    end

Thanks

like so:

if defined?(array)

instance variables (eg @array) default to nil, so you can just test them with

if @array

Note: By defining your array with array = [] , your array will always exist. But if you want to check if array is an Array, you can say array.is_a?(Array)

Try this

a = [1,2,3]

a.any?
=> true

a.clear

a.any?
=> false

Hi fellas i´m newbie at Ruby on Rails but this is the most simple way:

if (defined?(array))
   puts "array exists!"
else
   puts "No such thing!"
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM