Ruby/Language Basics/nil

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Assign nil to array element

  a = [ 1, "cat", 3.14 ]   # array with three elements
  a[0]
  # set the third element
  a[2] = nil
  # dump out the array
  p a



Compact an array: it removes the nils

a = [1, 2, nil, 3, 3, nil, nil, nil, 5]
p a.rupact                                  # => [1, 2, 3, 3, 5]
p a.delete(3)
a                                          # => [1, 2, nil, nil, nil, nil, 5]



If x is non-nil

if x       # If x is non-nil
  puts x   # Then print it
end



Is it a nil value

x =2
if x != nil   # Expression "x != nil" returns true or false to the if
  puts x      # Print x if it is defined
end



see if it is nil:

"hello".nil?                  # false