Ruby cheatsheet for beginners
Tags: ruby, beginners, programming
Published: 2021-04-06 15:09:44

##### Introduction to ruby:
*Ruby is an interpreted, high-level, dynamic, general-purpose, open-source programming language that focuses on simplicity and productivity. It was designed and developed in the mid-1990s by Yukihiro Matsumoto (also known as Matz in the Ruby community) in Japan.*

If you guys have already done coding in python, it'll be a bit simpler to understand the semantics of ruby even though under the hood ruby is completely different than python.
<img width="100%" style="width:100%" src="https://media.giphy.com/media/Ln2dAW9oycjgmTpjX9/giphy.gif">
First, we will talk about the common and frequently used methods.
```ruby
1.to_s # converts to a string, returns -> '1'
"1".to_i # converts to integer, returns -> 1
puts (1..2).to_a # range(..) operator can be used to create an array
# to_a method converts it to an array
puts ('a'..'g').to_a # similarly for characters
"1.5".to_i # can you tell what will be the output? returns -> 1 
```
By default **_to_i_** method will convert any float value to an integer
To sustain float value you can use
```ruby
"1.234".to_f # returns -> 1.234
```
Let's look at some basic arithmetic operations
```ruby
puts 1+2 # addition, returns 3
puts 2*5 # multiplication, returns 10
puts 4%3 # returns 1
puts 1.22312.floor # rounding the value to lowest returns 1
puts 1.22312.ceil # rounding the value to highest returns 2
puts 3.1223289.round(1) # limiting the decimal point to 1, returns -> 3.1
puts 'Hello, world!'.include?('Hello') # returns boolean value, it's case sensitive!
puts [1,2,3].include?(1) # same can be applied to arrays
puts 1/2 # returns 0, wondering why? 🤔
```
By default interaction with integer values will return an integer.
In order to return a float value do this
```ruby
puts 1/2.0 # add a decimal point, returns 0.5 😮
```
To check the length or size of an array or string
Both methods output the same results, prefer whichever suits you 🙃
```ruby
'ruby'.size # returns 4
'ruby'.length # Similarly, returns 4
```
Finally, the last one 😌
To get user input 
```ruby
puts "enter your name:"
name = gets # by default it adds a newline i.e \n at the end
name = gets.chomp # can be used to remove \n
```
Enough of basic, let's hop onto topic wise cheatsheet 
<img width="60%" style="width:60%" src="https://media.giphy.com/media/SWoRKslHVtqEasqYCJ/giphy.gif">
Let's get started with the first topic!
## 1. Arrays
##### To instantiate an array in ruby there are few ways to do it.
```ruby
# method 1, the simplest and most intuitive way of declaring array!
array = [1,2,3]
# method 2, using Array object
array = Array.new()
array1 = Array.new(3) # will create array of size 3
array2 = Array.new(3, "ruby") # ^ and will fill array with value->"ruby"
# for some dynamic values, you can use below
array3 = Array.new(5){|index| index = index * 3} # where index->index value of the array
# for multi-dimensional array you can create using below
array4 = Array.new(3){Array.new(3)} # this will create array of size 3x3 and each value will be "nil"
array5 = Array.new(3,0){Array.new(3,0)} # array of size 3x3 with each value->0
```
##### Common methods used for array manipulation
```ruby
prog_langs= ["ruby", "python", "javascript", "go"]
sorted_prog_langs = prog_langs.sort # returns a new array with sorted values
# If you don't want to return new array and wanna sort existing array instead 
prog_langs.sort! # "!" operator here is very handy and can be used with many methods in ruby to perform in-place operation 👌
# concurrently traverse both arrays
frameworks = ["ruby on rails", "django", "react", "Martini"]
prog_langs.zip(frameworks).each do |lang, framework|
  puts "#{lang} has framework: #{framework}"
end
# pop an element from an array
# by default ruby only pops element from tail of array 
# unlike python you cannot pop element based on index
frameworks.pop() # by default pops last element in array and returns popped element
# to remove element from the head of an array
frameworks.shift # by defaults remove one element from head
frameworks.shift(2) # removes first 2 elements, returns ["ruby on rails", "django"]
frameworks.push("spring") # appends to the array from tail
frameworks << "spring" # another alternative for push
# if arrays consists only of string types can use this format
frameworks = %w[ruby_on_rails django react Martini]
```
## 2. Strings
Basic operations on a string which is similar to most languages
```ruby
# declare and assign a value
string = 'hello, world!'
# Interesting fact, all strings are mutable in ruby this will most likely will change in upcoming ruby versions
# also this assignment can be used to remove space from string
string[6] = '' # each char is has an index including space, removes space from string variable
# concat string
string_1 = 'how are you?'
result = string + '' + string_1 # returns -> 'hello, world! how are you?'
# string literals or interpolation in ruby can be achieved using double quotes("")
language = "ruby"
experience = 3
puts "I have #{experience} years of experience in #{language}"
# interpolation can be done using same double quotes
puts "I have #{experience > 2 ? "good" : "ample"} amount of experience in #{language}"
# returns -> "I have good amount of experience in ruby"
# substitution using gsub method
a = "I have 3 years of experience in ruby"
a.gsub!("ruby", "python") # returns -> "I have nice amount of experience in ruby, "!" for in-place substitution"
a.gsub!(/\d/, 5) # use regex to replace, returns -> "I have 5 years of experience in ruby"
# downcase and upcase a string
language.upcase! # returns -> 'RUBY'
language.downcase! # reutrns -> 'ruby'
# to remove spaces from head and tail of string
b = " hello. "
b.strip # by default space is considered, you can pass your arg
# to check if a string start with a substring
# NOTE: both are case sensitive
c = "Whats your favorite programming language?"
c.start_with?('Whats') # returns -> true
c.end_with?('Language?') # returns -> false
```
## 3. Hash
Hash is equivalent to dictionaries in python.
There are various ways to create a Hash in ruby.
```ruby
hash = Hash.new # will create a empty hash -> {}
hash1 = Hash.new('test') # creates hash of default value 'test'
hash2 = {name:'bob', age:21}
puts hash2 # returns -> {:name=>'bob', :age=>21}
puts hash1[0] # returns 'test', as no value is set yet
# inserting a value
hash['language']='ruby'
hash['designation']='software engineer'
puts hash # returns -> {'language'=>'ruby', 'designation'=>'software engineer'}
# to check a key is present or not
hash.has_key?('language') # returns true
hash.key?('language') # alternative to has_key?
# to delete a key
hash.delete('language') # returns the value of that key
# merging two hashes
hash.merge!(hash2) # merges two hashes and changes are reflected in 'hash' variable
puts hash # returns -> {:name=>'bob', :age=>21, :language=>'ruby', :designation=>'software engineer'}
```
## Some bonus stuff!!
<img height="50%" width="50%" style="width:50%;height:50%" src="https://media.giphy.com/media/2iYnVCY4v9CGk/giphy.gif">
if you want to run terminal commands in ruby
```ruby
# using backticks you can execute these commands
response = `ssh <user>@<IP> 'cd /some/dir && cat somefile.txt'`
```
Also if any response is of JSON type
```ruby
# In order to avoid error while parsing, always do below
response = {"name":"bob","occupation":"Software engineer"}
# ruby will implicitly convert this into hash like below
# {:name=>"bob", :occupation=>"Software engineer"}
puts response["name"] # returns -> 👎 i.e nothing
puts response[:name] # Instead use symbols, returns "bob" 
```
But if you're fetching a response from a machine's logs or from an API, it might be stringified in that case you can use
```ruby
response = '{"name":"bob","occupation":"Software engineer"}'
# When using JSON.parse it won't convert keys to symbols
final_response = JSON.parse(response)
puts final_response["name"] # returns "bob"
```
<img width="60%" style="width:60%" src="https://media.giphy.com/media/l4pTjOu0NsrLApt0Q/giphy.gif">