Ruby Explained: Other Random Tidbits
This post will get into a few other random things that are really useful but usually skipped by beginners
So What is nil
? It represents nothing... literally. Before you assign a value to something, it starts as nil
, for instance an item in an array or a variable:
> my_arr = []
=> []
> my_arr[3]
=> nil # hasn't been assigned yet
Sometimes you want to know if a value or variable is nil
before doing something (because otherwise the operation would throw a bunch of errors at you). Use the method nil?
to ask whether it's nil or not beforehand.
> nil.nil?
=> true
> [].nil?
=> false # Waitasecond....
Why is []
not nil? The array itself exists so it isn't nil... it just happens to contain no values yet so it's empty. If we asked for the first value of that array using [][0].nil?
, that would be true