Ruby Language Overview

Ruby Basic Concepts

Published:
Last modified:

Ruby Console (Interactive Ruby): irb

Everything in Ruby, including nil and strings, is an object

Syntax

Assignment

Modules and Classes

Related methods in Ruby can be packaged in modules.

Modules are often explicitly imported or they can be imported automagically in frameworks that favours conventions like ruby on rails.

module ApplicationHelper
	# ....
end

Method definition

By convention, every method that ends with a question mark ? returns a boolean value.


irb(main):> "".empty?
=> true

Defining a method with def:

def message(str = '')
  return "empty string!" if str.empty?
  return "nonempty."
end

Comments

Comments start with the hash mark # (also called the pound sign and the octothorpe)

# This is a comment in ruby

Local variable assignment

Booleans

Comparisons

  • Equality comparison operator ==
  • Not equal comparison operator !=

Control flow

Conditional clause (if)

if-elsif-end


irb(main):> if "".empty? && !"a".empty? || "".length==0 
irb(main):>   puts "YOLO"
irb(main):> elsif !"".empty?
irb(main):>   puts "That is not YOLO"
irb(main):> end
YOLO
=> nil
irb(main):> puts "Hello" if "".empty?
Hello
=> nil

Strings

Strings in Ruby are specified with double quotes "a string" or single quotes'another string'. The main difference between them is that double quotes allows string interpolation "Hello #{name}" and escape sequences "\n" so it is encouraged to use them.

String concatenation is done with + sign: "foo" + "bar" or with interpolation:


irb(main):> sport="running"
=> "running"
irb(main):> "keep #{sport}"
=> "keep running"

Printing

To print a string there is the command puts and print.

The command puts stands for put string and is used to print strings.

puts includes a new line after showing the content and does not return anything (__nil__).

irb(main):> print "foobar"
foobar=> nil
irb(main):> puts "foobar"
foobar
=> nil
irb(main):> print "foobar\n"
foobar
=> nil

Return values

Data structures

Arrays

a = ["foo", "bar", "baz"]
  • Access specific array position
    • a[0]
    • a.first

Operator precedence

References

Uruguay
Marcelo Canina
I'm Marcelo Canina, a developer from Uruguay. I build websites and web-based applications from the ground up and share what I learn here.
comments powered by Disqus


Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.

Powered by SimpleIT Hugo Theme

·