DEV Community

Cover image for Ruby cheatsheet for beginners
Lakhan Jindam
Lakhan Jindam

Posted on

Ruby cheatsheet for beginners

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.

First, we will talk about the common and frequently used methods.

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 
Enter fullscreen mode Exit fullscreen mode

By default to_i method will convert any float value to an integer
To sustain float value you can use

"1.234".to_f # returns -> 1.234
Enter fullscreen mode Exit fullscreen mode

Let's look at some basic arithmetic operations

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? 🤔
Enter fullscreen mode Exit fullscreen mode

By default interaction with integer values will return an integer.
In order to return a float value do this

puts 1/2.0 # add a decimal point, returns 0.5 😮
Enter fullscreen mode Exit fullscreen mode

To check the length or size of an array or string
Both methods output the same results, prefer whichever suits you 🙃

'ruby'.size # returns 4
'ruby'.length # Similarly, returns 4
Enter fullscreen mode Exit fullscreen mode

Finally, the last one 😌
To get user input

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
Enter fullscreen mode Exit fullscreen mode

Enough of basic, let's hop onto topic wise cheatsheet

Let's get started with the first topic!

1. Arrays

To instantiate an array in ruby there are few ways to do it.
# 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
Enter fullscreen mode Exit fullscreen mode
Common methods used for array manipulation
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]
Enter fullscreen mode Exit fullscreen mode

2. Strings

Basic operations on a string which is similar to most languages

# 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
Enter fullscreen mode Exit fullscreen mode

3. Hash

Hash is equivalent to dictionaries in python.
There are various ways to create a Hash in 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'}
Enter fullscreen mode Exit fullscreen mode

Some bonus stuff!!


if you want to run terminal commands in ruby

# using backticks you can execute these commands
response = `ssh <user>@<IP> 'cd /some/dir && cat somefile.txt'`
Enter fullscreen mode Exit fullscreen mode

Also if any response is of JSON type

# 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" 
Enter fullscreen mode Exit fullscreen mode

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

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"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)