Ruby, lesson 2
A variable is a name that points at a value. You create one by assigning to it with =.
There is no keyword and no type to declare: Ruby works out the type from the value.
You can reassign a variable whenever you like, even to a value of a different type. The name simply starts pointing at the new value.
Every value in Ruby is an object, and every object knows its class. Ask with .class:
7, -3 or 1_000_000. Underscores are allowed to make
big numbers readable, and integers can grow as large as you need.92.5.2 exercises to try what you just read.
You will also see symbols such as :gold. A symbol is a lightweight, unchangeable name.
They show up a lot as hash keys, which you will use in lesson 7.
Local variable names start with a lowercase letter or an underscore and use snake_case:
lowercase words joined by underscores, like high_score or items_in_cart. Pick names that
say what the value means. total_price tells the reader far more than tp.
A name that starts with a capital letter is a constant. By convention constants are
written in SCREAMING_SNAKE_CASE. They are for values that should not change while the
program runs.
Ruby will let you reassign a constant, but it prints a warning. Treat that warning as a bug.
Inside a double-quoted string, #{ } runs the Ruby code inside the braces and drops the
result into the text. This is called interpolation, and it is the usual way to mix values
into a message.
Single-quoted strings print #{ } literally. That is the main practical difference between
the two kinds of quotes.
Strings also have handy methods. "Mira".length is 4, and "Mira".upcase is "MIRA".
You call a method on a value with a dot.
The starter reads a first name and a city, one per line, into two variables. Use string interpolation to print a three-line badge:
where <n> is the length of the name. For the input
the output is
Define three constants, SECONDS_PER_MINUTE = 60, MINUTES_PER_HOUR = 60 and
HOURS_PER_DAY = 24. Then store the number of days in a week in a variable called days,
and use the constants to print:
The program reads no input.
player = "Mira"
level = 7
health = 92.5
online = trueputs 7.class # Integer
puts 92.5.class # Float
puts "Mira".class # String
puts true.class # TrueClass
puts nil.class # NilClassMAX_LIVES = 3
TAX_RATE = 0.2name = "Mira"
level = 7
puts "#{name} reached level #{level}!" # Mira reached level 7!
puts "Next level: #{level + 1}" # Next level: 8
puts 'Single quotes: #{name}' # Single quotes: #{name}Hello, my name is <name>.
I live in <city>.
My name has <n> letters.Ada
LondonHello, my name is Ada.
I live in London.
My name has 3 letters.A week has 604800 seconds.