Today I worked on ordering my library as well as hashes and symbols. I learned about def
methods and parameters. Also learned about rev=false
and this causes def
methods to default to false if the user types in 2 arguments. I should also remember to put ==
in conditionals, I've been making the mistake of putting =
which is used for assignment.
Building on methods is great for using code over and over without having to retype things but it is also great for abstracting or simplifying your program.
There are two ways to write hashes
Hash literal notation is new_hash = { "one" => 1 }
new_hash = Hash.new`
or
Along with false, nil is one of 2 non-true values in ruby. Every other object is regarded as truthful. False means not true. nil is ruby's way of saying nothing at all.
You can add key/value pairs in Hash.new
like this:
empty_hash = Hash.new
empty_hash.store(:key, "value")
default_hash = Hash.new("default")
If you want to provide a default value for any key that doesnt exist in the hash, pass this argument . This will return
default instead of
nil`. The hash is empty until you explicitly add key-values when using this method.
symbols- can only be one copy of a particular symbol at a given time. They can start with a :
and spaced with a _
. They are primarily used with hash keys for referencing method names. They are immutable meaning they cant be changed once created. Only one copy exists at a given time, saving memory. Symbol-as-keys are faster than string-as-keys. .to_s
is to string while .to_sym
converts to symbol. .intern
is also another way to convert to a symbol.
With the new update, symbol syntax has changed to where you put the :
after the symbol instead of before it, you dont need the hash rocket anymore.
Top comments (0)