Getting started with Ruby. Data types, User Input, Installation

Wed Nov 15 2023

Let's get started with Ruby.

To install Ruby on our computer we need to download the installer file from https://rubyinstaller.org/. The installation process is smooth and very straightforward.

Ruby and VSCode

First thing we need to do if we want to use VSCode is let it do its magic and get the right extensions. The first one is Ruby which is a package of three other extensions: Ruby LSP, Ruby Sorbet and VSCode rdbg Ruby Debugger. This is all we need for analyzing Ruby code and enhancing our user experience. The extension recommends using a Spinel dark theme for better semantic highlighting.

Second extension is Code Runner, which is a useful tool when working not only with Ruby, but also many other programming languages. Here we use the shortcut CTRL + ALT + N to run our Ruby code.

We can also run it by opening the terminal and entering: ruby filename.rb.

Comments

For single-line comments in Ruby we use #.

# This is a comment example

Multiple-line comments need to have =begin and =end, both in separate lines

=begin
this is a comment example as well
=end

Print/Puts

Ruby is going to execute the instructions in the order that we write them.

puts "Hello World" (pushes what follows one line below)

print "Hello World" (whatever follows will print next to it in the same line)

Variables

Variables in Ruby can store different types of data and can be updated throughout your program. The naming convention is that these variables should start with a lowercase letter and words should be separated by underscores.

→ Local variables

person_name = "Harry"
person_age = "35"

puts (person_name + " is " + person_age + " .") // Harry is 35.

person_age = "40"

puts (person_name + " is " + person_age + " .") // Harry is 40.

Data types

→ Strings

name = "Lena Esposito" // String

To put a quotation mark inside a string we use \ (a backslash).

puts "My name begins with \"L\"" // My name begins with "L"

To print something on a diffrent line we use \n.

Strings methods

While I will use a variable name, note that you don't have to create a variable to use these fnctions.

name = "Lena Esposito"
puts name.upcase() // LENA ESPOSITO

Other methds include:
  • capitalize() (capitalizes only the first letter),
  • downcase() (to lower case),
  • reverse() (prints the string in reverse),
  • strip() (gets rid of white space),
  • split(" ") (splits string where there are spaces. It returns an array.),
  • length() (prints length as a number),
  • include? "string" (returns a boolean value),
  • index("L") (returns the index of the character or the the index of where the string starts),
  • gsub(/s/, "th") (looks for "s" and replases it with "th")

String interpolation

print "What's your first name?"
first_name = gets.chomp.capitalize!
print "What's your last name?"
last_name = gets.chomp.capitalize!
print "What city do you live in?"
city = gets.chomp.capitalize!
print "What's the abbreviation of the state you come from?"
state = gets.chomp.upcase!

puts "My name is #{first_name} #{last_name}. I live in #{city}, #{state}."

// My name is Lena Esposito. I live in Newport, GWENT.

! at the end of capitalize modifies the value contained within the variable itself and the variable will be capitalized the next time it's used.

To access individual characters we use the index number in square brackets. We also use them to print out a range of characters.

puts name[0] // L

puts name[0, 3] // Len (start with 0, stop before 3)

→ Numeric

Ruby distinguishes between integers and decimal numbers. If we operate on integers, we are goint to get an integer back, i.e. 10 / 4 will give us 2, while 10/4.0 will print a more accurate decimal number - 2.5.

age = 65 // Number (integers and floats/decimal)

In order to print a number next to a string we need to convert it to a string with .to_s.

number = 13
puts ("My favourite number is " + number.to_s) // My favourite number is 13

Number methods

There are a bunch of methods that we can call on numbers.

number = -13
puts number.abs() // 13 (returns the absolute value)

number = 13.6594513
puts number.round() // 14 (rounds the number)

Other functions include:
  • ceil() (rounds it up),
  • floor() (rounds it down),
  • Math.sqrt(number) (prints square root of a number),
  • include? "string" (returns a boolean value)
  • index("L") (returns the index of the character or the the index of where the string starts)

Math

Some of the arithmetic operators that we can use for calculations in Ruby are: Addition (+), Subtraction (-), Multiplication (*), Division (/), Exponentiation (** - raises one number to the power of the other) and Modulo (%)

→ Booleans

isfemale = true // Boolean

→ Arrays

Array is a container for different types of data.

my_array = [ "banana", "Hello!", 3.1242, true, 56 ] // array

Accessing items in the array

months = Array["April", "June", "August"]

puts months    // April
                  June
                  August

puts months[0]    // April

puts months[0, 2]    // April
                        June

puts months[-1]    // August

months[0] = "March"

puts months[0]    // March

Creating a new array

months = Array.new

months[0] = "March"
months[3] = "May"

puts months    // March
                  

                  May

Array methods

  • length() (prints length as a number),
  • include? "item" (returns a boolean value)
  • reverse() (prints the array items in reverse),
  • sort() (sorts items alphabetically - only if all items are strings),

→ Hashes and Symbols

Hashes store data as key and value pairs. They are also called dictionaries and are often used for abbreviations. If the key describes what is in the value we call it literal notation. All keys in a hash need to be unique.

Keys can be strings or symbols. Symbols are used either as hash keys or for referencing method names. They're also immutable (can't be changed).

Note that in Ruby 1.9 the syntax of symbols in hashes changed and now you can omit the first colon and use ":" instead of "=>".

own_hats = { "Lena" => 5, "Alice" => 20, "Jacob" => 1 } // hash

my_symbols = {:ln => "Lena", :al => "Alice", :jc => "Jacob"} // symbols

states = {
    "California" => "CA",              OR :California          OR       California: "CA"
    "New York" => "NY",                                                 New York: "NY"
    "Pennsylvania" => "PA"                                              Pennsylvania: PA
}

puts states
    // {"California"=>"CA", "New York"=>"NY", "Pennsylvania"=>"PA"}

puts states["New York"]     // NY

You can create a hash using Hash.new. Note that Hash needs to be capitalized for that purpose. The created hash is empty.

colours = Hash.new

Adding to a hash

colours["warm"] = "red"

Removing from a hash

colours.delete("warm")

Default value

If a hash has a default value, then it will print it when we try to access a non-existent value.

empty_hash = Hash.new("default value")

puts empty_hash["hello"]        // default value

Accessing Hash Values

puts colours["warm"]            // red

Iterating Over Hashes

capitals = {
  "Poland" => "Warsaw",
  "England" => "London"
}

capitals.each {|country, capital|
puts "The capital of #{country} is #{capital}."
}

// The capital of Poland is Warsaw.
   The capital of England is London.

capitals.each {|country, capital|
puts capitals[country]
}
// Warsaw
   London

Filtering through hashes

To filter through a hash we use .select, .each_key or .each_value.

grades = { alice: 100,
  bob: 92,
  chris: 95,
  dave: 97
}

a = grades.select { |name, grade| grade <  97 }
puts a          // {:bob=>92, :chris=>95}

b = grades.select { |k, v| k == :alice }
puts b          // {:alice=>100}

initials = { PL: 1, KI: 2, GG: 3 }

initials.each_key { |k| print k, " " }      // PL KI GG
    
initials.each_key { |v| print v, " " }      // 1 2 3

Converting strings to symbols

We use .to_sym and .intern in order to convert strings to symbols.

strings = ["One", "Two", "Three"]
symbols = []
strings.each {|string|
  symbols.push(string.to_sym)
}
puts symbols        // [:One, :Two, :Three]

Check if symbol

:LA.is_a? Symbol

→ Nil

In Ruby, if you try to access a key that doesn't exist, you get the non-true nil value. Nil doesn't mean false, but nothing.

money = nil

User Input

puts "Enter Your Name: "
name = gets.chomp()  // if not for .chomp(), the line below would print on two lines, instead of just one
puts ("Hello " + name + "! How are you today?")

Adding numbers from the user input

Let's add some integers first.

puts "Enter a number: "
num1 = gets.chomp()          // let's say we enter 2
puts "Enter another number"     
num2 = gets.chomp()          // now we enter 4

puts (num1 + num2)           // this will print 24 as both the outputs are strings

puts (num1.to_i + num2.to_i)  // .to_i converts the number we enter from a string to an integer
            // this will print 6

The situation is different when we work with decimals.


puts "Enter a number: "
num1 = gets.chomp()          // let's say we enter 2.5
puts "Enter another number"     
num2 = gets.chomp()          // now we enter 4

puts (num1.to_f + num2.to_f)  // .to_f will convert the outputs into 
                                floating points/decimal numbers
// this will print 6.5

Note than we could also put .to_f directly after chomp()

Sources:

Codecademy

Illustration for the Getting started with Ruby. Data types, User Input, Installation

Comments (0)


Be the first to leave a comment