DEV Community

Linda Solis
Linda Solis

Posted on

Ruby Codeacademy Learnings Notes

  • Ruby file extension script*.rb*
  • Commenting two types of comments
    Single line comments
    start with a #.
    Multi line comments start with =begin and end with =end.

  • put and print commands can be used to display text in the console

  • Variables: There are four different types of variables in Ruby
    Local variables
    must begin with a lowercase letter or _. These variables are local to the code block of the method they are declared in.
    Instance Variables
    Instance variables begin with an @ symbol. Instance variables are variables that belong to an object.
    Class Variables
    Class variables begin with an @@ sign. Class variables are available across different objects shared by all the descendants of the class. They must be initialized before use.
    Global Variables
    Global variables begin with an $ symbol. While Class variables are not available across different classes, global variables are. Its scope is global, meaning that it can be accessed from anywhere in the program.

  • Object Methods
    everything in Ruby is an object, are built-in abilities of objects. To access an object’s methods, you need to call it using a . and the method name.
    example: # Method to get the string reversed
    print var*.reverse*
    # ymedacedoc
    .length Ruby will return the length of the string (that is, the number of characters—letters, numbers, spaces, and symbols).
    .upcase and .downcase
    returns a version of the string in all uppercase or all lowercase

    example: name = "Jamie"
    puts name*.downcase.reverse.upcase*
    # EIMAJ

  • Strings
    single quotation marks (‘’) or double quotation marks (“”)

  • string interpolation
    used to insert the result of Ruby code into a string
    example: age = 30
    print "I am #{age} years old"
    # "I am 30 years old"

  • Get user input in Ruby
    using gets.chomp
    gets is the method used to retrieve user input.
    Ruby automatically adds a new line after each bit of input, so chomp is used to remove that extra line.
    example: print "Type your name and press Enter: "
    name = gets.chomp
    puts "My name is #{name}!"

  • Modulo
    returns the modular value, the remainder, when two numbers are divided.
    example: puts 5*.modulo(3)
    # Output: **2
    *
    5 is divided by 3 and the remainder is 2

  • User input Simple Program:
    print "What's your first name? "
    first_name = gets.chomp
    first_name.capitalize!

print "What's your last name? "
last_name = gets.chomp
last_name.capitalize!

puts "Your name is #{first_name} #{last_name}!"

Top comments (0)