Skip to content
This repository has been archived by the owner on May 23, 2020. It is now read-only.

Latest commit

 

History

History
343 lines (297 loc) · 8.29 KB

cheatsheet.md

File metadata and controls

343 lines (297 loc) · 8.29 KB

Common Methods in Ruby

.to_a converts almost anything to an array.

puts (1..10).to_a

Variables

Local variables are written in all small letters separated by underscore. E.g. my_name, simon. To get input from user, gets.chomp is used.

input1 = get.chomp

By default, Ruby adds a new line after input. chomp removes that extra new line.

Control Flow

if and elsif works in the same way as other languages.

num = Integer(gets.chomp)
if num > 0
    print "Number is positive"
elsif num < 0
    print "Number is negative"
else
    print "Number is 0"
end

If elsif else block end with end.

The condition inside if should evaluate to true for the block to be executed. In unless the condition should evaluate to false.

hungry = false
unless hungry
  puts "I'm writing Ruby programs!"
else
  puts "Time to eat!"
end

There is another syntax of using unless and if which is similar to how we put conditions in our day-to-day conversations. expression if boolean expression unless boolean

jobNotDone = false
print 'Good work!!' unless jobNotDone

No need to write end in the end of the statement.

Ruby also supports ternary operator: boolean ? Do this if true: Do this if false

Relational, Assigment and Comparison Operators are same as for other common languages: = == > >= < <= !=
Logical and Boolean operators: && || !
Complex expressions can be created using these operators: E.g. (x && (y || w)) && z
Expressions in parentheses are always evaluated before anything outside parentheses.

case is an alternative to if else statements.

case language
  when "JS"
    puts "Websites!"
  when "Ruby"
    puts "Web apps!"
  else
    puts "I don't know!"
end

The above can also be like as below: ;P

case language
  when "JS" then puts "Websites!"
  when "Ruby" then puts "Web apps!"
  else puts "I don't know!"
end

Loops and Iterators

Use of while:

i=0
while i<5
    puts i
    i=i+1
end

Use of until: continues looping until the condition given turns to be true. It is compliment to while.

counter = 1
until counter == 11
    puts counter
    counter+=1
end

This prints from 1 to 10, each number in new line. Note: These operators are supported in Ruby: += -= *= /=

When you don't know how many times you have to loop in, a different syntax of for can be used.

for num in 1...10
  puts num
end

This will print numbers from 1 to 9 each in different line. 1...10 will print 1 to 9 1..10 will print 1 to 10

Ruby supports iterators. One such simple method is loop.

loop { print "Hello there!!" }

The curly braces {} are interchangeable with keywords do and end.

i = 0
loop do
  i += 1
  print "#{i}"
  break if i > 5
end

A condition is given inside the block which will be used to decide when to break the loop. The next keyword can be used to skip over certain steps in the loop.

i = 20
loop do
  i -= 1
  next if i%2!=0
  	puts "#{i}"
  break if i <= 0
end

This code snippet will print only even numbers from 18 to 0.

.each method is more powerful iterator.

array = [1,2,3,4,5]
array.each do |x|
  x += 10
  print "#{x}"
end

do and end keywords can be replaced by curly braces {}.

The .times method is like a super compact for loop: it can perform a task on each item in an object a specified number of times.

10.times do
  print "Hello there!"
end

.upto and .downto can also be iterate through a start and end value. An inclusive range is formed.

"L".upto("P") { |num| print num, " " }
# Prints L M N O P

Data Structures

Arrays in Ruby are declared as:

my_array = [1,2,3,4,5]

2D array is declared as:

my_2d_array = [[0,0],[0,0]]

Hashes in Ruby are sort of like JavaScript objects or Python dictionaries. A hash is a collection of key-value pairs. Values are assigned to keys using =>.

my_hash = { "name" => "Eric",
  "age" => 26,
  "hungry?" => true
}
puts my_hash["name"]

This is literal notation.

An empty hash is declared as:

my_hash  = Hash.new
my_hash["key"] = "value"

To traverse through a hash, .each iterator is used

family = { "Homer" => "dad",
  "Marge" => "mom",
  "Lisa" => "sister",
  "Maggie" => "sister"
}
family.each { |x, y| puts "key: #{x}: value: #{y}" }

Hash can have default values.

h = Hash.new("nothing here")
puts h # {}
puts h["kitty"] # nothing here

.sort_by function is used to sort elements in hash. It returns an array of array.

frequencies = frequencies.sort_by do |key, value|
  value
end

The above code snippet sorts the hash frequencies as per its value in ascending order by default.

Sorting Methods and Blocks

Methods are defined using the keyword def.

def welcome
  puts "Welcome to Ruby!"
end

A method that takes parameters and returns the sum. return keyword is used.

def add(a,b)
  return a+b
end

Blocks can be defined with either the keywords do and end or with curly braces ({}).

[1, 2, 3, 4, 5].each do |i| puts i*5 end

.sort! method sorts array. Be default, ascending.

my_array = [1,4,2,6,3]
my_array.sort!

Combined Comparison Operator: ( <=> ) This returns 0 if first operand is equal to second, 1 if first operand is greater second else -1.

name_1 = "Anna"
name_2 = "Betti"
puts name_1 <=> name_2

.sort! accepts a block which can be used to sort array in descending order as well.

books.sort! { |firstBook, secondBook| firstBook <=> secondBook } #for ascending order
books.sort! { |secondBook, firstBook| firstBook <=> secondBook } #for descending order

Hashes and Symbols

In Hashes, if you are trying to access a key which do not exist, Ruby return nil. It is Ruby's way of saying nothing at all. => is called the hash rocket symbol.

Hashes can also be defined using symbols:

menagerie = { :foxes => 2,
  :giraffe => 1,
  :weezards => 17,
  :elves => 1,
  :canaries => 4,
  :ham => 1
}

Note: Hash lookup is faster with symbol keys than with string keys.

Symbols are not strings. There can be different strings all having the same value, there's only one copy of any particular symbol at a given time. Symbols always start with a colon (:). They must be valid Ruby variable names. These are mainly used as hash keys or for referencing method names.

"string == :string #false

The .object_id method gets the ID of an object. It's how Ruby knows whether two objects are the exact same object.

puts "string".object_id
puts :symbol.object_id

.to_s and .to_sym can be used for interconversion between strings and symbols.

:hellothere.to_s
# ==> "hellothere"

"hellothere".to_sym
# ==> :hellothere

.inter works the same as .to_sym.

In Ruby 1.9, the hash definition syntax changed.

new_hash = { 
  one: 1,
  two: 2,
  three: 3
}

The keys are still symbols.

.select method can be used on hashes for filtering out data based on some condition.

grades = { rita: 100,
  mita: 97,
  ayush: 56,
  jane: 83
}

grades.select { |name, grade| grade <=  97 }
# ==> { :rita => 100, :mita => 97 }

Every time in .each block for hashes we have to define variables for key as well value. Ruby has two methods .each_key and .each_value to overcome this problem.

my_hash = { one: 1, two: 2, three: 3 }

my_hash.each_key { |k| print k, " " }
# ==> one two three

my_hash.each_value { |v| print v, " " }
# ==> 1 2 3

Data can be deleted from hash using the method .delete(key)

my_hash.delete(key)

Refracting

The conditional assignment operator: ||=. It assigns a value to a variable only when it is not already assigned.

favorite_book = nil
puts favorite_book #nil

favorite_book ||= "Cat's Cradle"
puts favorite_book #Cat's Cradle

favorite_book ||= "Why's (Poignant) Guide to Ruby"
puts favorite_book #Cat's Cradle

favorite_book = "Why's (Poignant) Guide to Ruby"
puts favorite_book #Why's (Poignant) Guide to Ruby

If there are no return statement in a function and a value is expected from that function, then the method will return the result of the last evaluated expression.

def add(a,b)
  a + b
end # this method will return the sum of two numbers