Week 8 - Ruby Cheatsheet

Hashes

A hash is a collection of key-value pairs like this: "employee" => "salary". It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index.

First, you will need to create a new hash.

months = Hash.new

You can also create it with a default value, which is otherwise just nil.

months = Hash.new("month")

or

months = Hash.new "month"

But the hashes are good for keys and values.

months = {"1" => "January", "2" => "February"}

puts "#{months.keys}" => This will print ["1", "2"]

puts "#{months.values}" => This will print ["January", "February"]

In order to delete a value in a hash you could use delete method like below.

months.delete("1") => This will delete key "1" and value "January".

months.delete("2") => This will delete key "2" and value "February".

Arrays

Ruby arrays are ordered, integer-indexed collections of any object. Each element in an array is associated with and referred to by an index.Ruby arrays can hold objects such as String,

Integer, Fixnum, Hash, Symbol, even other Array objects. Ruby arrays are not as rigid as arrays in other languages. Ruby arrays grow automatically while adding elements to them.

There are many ways to create or initialize an array. One way is with the new class method:

names = Array.new

You can set the size of an array at the time of creating array:

names = Array.new(20)

OR

nums = Array.[](1, 2, 3, 4,5)

OR

nums = Array[1, 2, 3, 4,5]

Strings

The simplest string literals are enclosed in single quotes (the apostrophe character). The text within the quote marks is the value of the string.

For example:

String notation:

"This is a string." #single quotes can also be used but string interpolation won't work on single-quoted strings

puts "Two plus two is #{2+2}." => Two plus two is 4.

Integers

Ruby integers are objects of class Fixnum or Bignum. The Fixnum and Bignum classes represent integers of differing sizes.

Both classes descend from Integer (and therefore Numeric). The floating-point numbers are objects of class Float, corresponding to the native architecture's double data type.

The Complex, BigDecimal, and Rational classes are not built-in to Ruby but are distributed with Ruby as part of the standard library.

When numbers are stored as strings, you can use .to_i method to make it integer.

numbers = "123" <= numbers is in strings form.

numbers + 4 will be invalid since you cannot add 4 to a string.

numbers.to_i + 4 => This will result in 127 because 123 is now an integer so you can add 4 to it.

There are number of methods that you can use for integers.

next is a way to get next number.

1.next => This is 2.

(-1).next => This is 0.

When you want to round up your number, you need to use round method.

This rounds integer to a given precision in decimal digits.

1.round => 1

1.round(2) => 1.0

15.round(-1) => 20