the difference is that a string is mutable and a symbol is immutable. Meaning only one copy of a symbol is gonna be created through the duration of the program’s execution. foo = “hello world” bar = “hello world” foz = :hello_world baz = :hello_world # let’s check the object id’s of this so we know what’s going on.
method say_hello - name of the the method name - parameter puts “hello #{name}” - expression inside function that prints out hello and the name from the parameter. end - closes the method definition Methods - Syntax
Ruby 2.0 people usually make use of the “options” parameters. def say_hello(first_name: “Foo”, last_name: “Bar, location: nil) puts “#{first_name} #{last_name}” puts “#{location} is a cool place” if location end def say_hello(options = {}) puts “#{options[:first_name]} #{ options[:last_name]}” puts “#{options[:location]}” end
and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. - Ruby Docs spanish = { hello: “hola”, cool: “fresco” }
with that key. spanish.delete(:hello) => “hola” This will also return the value of the deleted key-value pair. Passing an optional block - will be called if key doesn’t exist spanish.delete(:hello) { |key| puts “#{key} doesn’t exist” }
true or false value, if the key or the value exists in the hash spanish.has_key?(:hello) => true spanish.has_key?('hola') => false spanish.has_value?('hola') => true spanish.include?(:cool) => true
pass it a block that receives two arguments (the key and the value). spanish.each {|key, value| puts "#{key.to_s} is #{value} in spanish"} hello is hola in spanish cool is fresco in spanish => {:hello=>"hola", :cool=>"fresco"}
a block and it receives the “key” argument puts "List of words" spanish.each_key {|key| puts "#{key.to_s}"} hello cool => {:hello=>"hola", :cool=>"fresco"}