Setting default values for variables can be very useful in ruby. There are a variety of ways to do it and the way you assign default values all depends on how the value is being stored. Here's some examples:
Default variables in a method or function:
def print_my_name(name = "John Doe") puts name end print_my_name # => "John Doe"
This is the old fashioned way to set default variables in a method...Sure, it works, but it has one major drawback. The values you pass into this method have to be order, which can be annoying if you want to assign only one custom value in a method, and that arguments is at the end of the list of arguments passed into the method. Instead, I like to pass in a hash of value into a method and then handle default value assignment inside the method, instead of in the the method definition:
def print_my_name(options = {})
options[:name] ||= "John Doe"
puts options[:name]
end
print_my_name :name => "John Doe" # => "John Doe"
This lets you pass in any value as you please, in any order, since everything is stored in a hash! This also has a slight downside to it: Since we're working with hash members, we have to assign default values to hash items the right way. This can vary depending on the data type of the variable. We can't Let's take a look:
def print_my_information(options = {})
options[:name] ||= "John Doe" # default value for a string
options[:age] ||= 25 # default value for an integer/float
options[:hates_pickles] = true if options[:hates_pickles].nil? # default value for a bool
return options
end
print_my_information :name => "Dave", :age => "28", :hates_pickles => false # => {:age=>"28", :hates_pickles=>false, :name=>"Dave"}
I like to use ruby's ||= operator, which checks a variable to see if it's defined, nil, or false. This works great for strings, chars, integers, and floats, but is horrible for booleans values(aka bools) because if you pass in a value for a bool that's false, it will get reassigned if you use the ||= operator, so never use this operator for default bool values. ever. If you make reference to an undefined hash item, ruby will return nil, so we can assign default bool values by checking if the hash key you're looking for is nil:
options[:hates_pickles] = true if options[:hates_pickles].nil?
This is one good way to handle default values in an method in ruby, and can come in very handy!





Today is Opal's first birthday! 
