Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 14, 2020 06:51 pm GMT

My beloved Ruby Cheat Sheet

Here is my cheat sheet I created along my learning journey. If you have any recommendations (addition/subtraction) let me know.

Variables declaration

# stringfull_name = 'Mike Taylor'# integercount = 20# floatbook_price = 15.80# booleansactive = trueadmin_user = false#Arrayfruits = ['Appel', 'Orange', 'Banana']#Conditional assignmenttitle = custom_title || Default title 
Enter fullscreen mode Exit fullscreen mode

print a string to the screen

#print with line breakputs 'This string will print on screen'#print with no line breakprint 'The string will print with no line break'
Enter fullscreen mode Exit fullscreen mode

string methods

# get string number of characters'This is a string'.length  # 16#check if the string is empty'Hello World'.empty?   # false''.empty?   # true#convert all characters to uppercase'hello world'.upcase  # HELLO WORLD#convert all characters to lowercase'HI'.downcase  # hi#convert first characters to uppercase and the rest to lowercase'mikE'.capitalize  # Mike#remove white space'  This is a string with space  '.strip #return a string left justified and padded with a character'hello'.ljust(20, '.')  # 'hello...............'#check if a string include character(s)'hello World'.include? 'World'. # true #chaining 2 or more methods'Hello World'.downcase.include? 'world' # true#index position (start at postion 0)'Welcome to this web site'.index('this') # 11#return string character(s) (start at position 0)'This is a string'[1]  # h'This is a string'[0..3]  # This'This is a string'[-1]  # g (last character)#replace first sub string'Hello dog my dog'.sub 'dog', 'cat'. # Hello cat my dog#replace all sub string'Hello dog my dog'.gsub 'dog', 'cat'. # Hello cat my cat#split a string into an array'Apple Orange Banana'.split ' '  #['Apple', 'Orange', 'Banana']# get console keyboard inputinput = gets# get input and chomp last char (ex. new line)input = gets.chomp# get command-line arguments (ex. ruby main.rb arg1 arg2)puts ARGV  # ['arg1', 'arg2']ARGV.each { |option| puts option }
Enter fullscreen mode Exit fullscreen mode

Numbers

number.round 2.68  # 3number.floor 2.68  # 2number.ceil 2.68   # 32.next  # 3puts 3 / 2    # 1 (integers with integer result integer)puts 3 / 2.0  # 1.5 (float with integer result float)puts 2.even?  # trueputs 2.odd?   # false# Random numberrandom_number = rand(1..100)
Enter fullscreen mode Exit fullscreen mode

Loop

loop do  puts "Stop loop by using 'break' statement"  puts "Skip one occurence by using 'next' statement"endwhile number < 100  puts number  number += 1end# Range(1..10).each { |i| puts i }(1..10).each do |i|  puts iend10.times { puts "Hello World" }
Enter fullscreen mode Exit fullscreen mode

Conditionals statement

# Equal ==   And &&   Or ||   Not !if action == 1  puts "action 1"elsif action < 5  puts "action not 1 but less than 5"else  puts "action greater than 5"end#Unless (negated if)puts 'The user is not active' unless active == true#Ternary operatoractive ? 'The user is active' : 'The user is not active'#Truthy or falsy# false and nil equates to false. # Every other object like 1, 0, "" are all evaluated to true# case when elsecase pointswhen 0  "Not good"when 1..50  "Better but not great"when 51..70  "Thats good!"when 71..99  "Great"when 100  "Perfect"else  "Score error"
Enter fullscreen mode Exit fullscreen mode

Array access

fruits = ['Apple', 'Orange', 'Banana']fruits = %w(Apple Orange Banana) fruits.length # 3fruits.first  # Applefruits.last   # Bananafruits[0]     # Applefruits[-2]    # Orangefruits[3]     # nilfruits[1..2]  # ['Orange', 'Banana']# iterationfruits.each do { |fruit| puts fruit } fruits.each_with_index do |fruit, index|  puts fruit  # Apple  puts index  # 0end
Enter fullscreen mode Exit fullscreen mode

Array Methods

fruits.include? 'Orange'  # true[1, 5, 2, 4, 3].sort  # [1, 2, 3, 4, 5][1, 2, 3].reverse  # [3, 2, 1]fruits.push 'Strawberry' # append at the endfruits <<  'Raspberry' # append at the endfruits.unshift 'Strawberry' # Append in frontfruits.pop # remove lastfruits.delete_at(0) # remove first elementfruits.shift  # remove the first elementfruits.join ', '  # 'apple, orange, banana'
Enter fullscreen mode Exit fullscreen mode

Convert between type

123.to_s   # convert number to string "123""123".to_i # convert string to integer 123"123".to_f # convert string to float 123.0#convert to array(1..10).to_a  # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]('a'..'e').to_a # ['a', 'b', 'c', 'd', 'e']
Enter fullscreen mode Exit fullscreen mode

Hash

product = {}product['title'] = "Mac Book Pro"product[:price] = 1599.99product = { 'title' => 'Mac Book Pro', 'price' => 1599.99 }product = { title: 'Mac Book Pro', price: 1599.99 }puts product.fetch(:cost, 0)  # return default value 0product.keys   # [:title, :price]product.values # ['Mac Book Pro', 1599.99]product.each do |key, value|   puts key  puts valueend
Enter fullscreen mode Exit fullscreen mode

Date and time

Time.now.utc    # 2020-12-13 03:17:05 UTCTime.now.to_i   # Timestamp 1607829496christmas = Time.new(2020, 12, 25)  #puts christmas.wday # return 5 (Thursday)now = Time.now  # current time: 2020-12-13 03:08:15 +0000now.year    # 2020now.month   # 12now.day     # 13now.hour    # 3now.min     # 8now.sec     # 15now.sunday? # truepast = Time.now - 20  # return current time minus 20 secondspast_day = Time.now - 86400 # 60 secs * 60 mins * 24 hourspast_day = Time.now - 1.day # work only in Rail#Format Time# %d    Day of the month (01..31)# %m    Month of the year (01..12) Use %-m for (1..12)# %k    Hour (0..23)# %M    Minutes# %S    Seconds (00..60)# %I    Hour (1..12)# %p    AM/PM# %Y    Year# %A    Day of the week (name)# %B    Month (name)time = Time.newtime.strftime("%d of %B, %Y")    # "25 of December, 2020"
Enter fullscreen mode Exit fullscreen mode

Regular Expression (editor: www.rubular.com)

zip_code = /\d{5}/"Hello".match zip_code  # nil"White House zip: 20500".match zip_code  # 20500"White House: 20500 and Air Force: 20330".scan zip_code # ['20500', '20330'] "Apple Orange Banana".split(/\s+/) # ['Apple','Orange', 'Banana']
Enter fullscreen mode Exit fullscreen mode

Functions

def greeting(name = 'John')  # = default argument value  "Hello #{name}"  # implicit returnendputs greeting('Paul')  # Hello Paul# variable number of argumentsdef greeting(*names)  names.each { |name| puts name }end#naming parametersdef display_product(price, options = {})  puts price, options[:hidden], options[:rounded]enddisplay_product 1599, hidden: false, rounded: true
Enter fullscreen mode Exit fullscreen mode

Map, Select and Reduce

#map (return a modified array)names = ['paul', 'john', 'peter']names_capitalize = names.map do |name|  name.capitalizeend# ['Paul', 'John', 'Peter']# short hand versionnames_capitalize = names.map { |name| name.capitalize }# Symbol to procnames_capitalize = names.map &:capitalize#select (return matching)products = [  { name: 'Mac Book Pro', active: true, price: 1599.99 },  { name: 'iWatch', active: false, price: 599.99 },  { name: 'iPad Pro', active: true, price: 699.99 },]active_product = products.select { | product | product[:active] }#reduce (return one)total = products.reduce(0) do |total, product|   total = total + product[:price]endputs total  # 2899.97
Enter fullscreen mode Exit fullscreen mode

Module

module Display  def hello    puts 'Hello'  endend# Mix inclass Customer  include DisplayendCustomer.new.hello# Module as namespacemodule Person  class Customer    def initialize(name)      @name = name    end  endendcustomer = Person::Customer.new('Mike Taylor')# Constantmodule Contact  ACCESS_KEY = 'abc123'  class Person      ACCESS_KEY = '123abc'  endendputs Contact::ACCESS_KEYputs Contact::Person::ACCESS_KEY#Module or class private methodmodule Display...def initialize  greetingendprivate  def greeting    puts 'hello'  endend
Enter fullscreen mode Exit fullscreen mode

OOP

# class declarationclass Productend# object instantiationproduct = Product.new # class declaration with constructor and instance variablesclass Product  def initialize(name, price, active)    @name = name    @price = price    @active = active  endendproduct = Product.new 'Mac Book Pro', 1599, true# attribute accessor (get & set)class Product  attr_accessor :name, :price  # read and write  attr_reader :name   # read only  attr_write :price  # write only  ...end...puts product.price  # 1599# instance methodclass Product  ...  def price_with_tax    # reference to @price directly is not recommended    self.price + (self.price * tax_percent / 100)    # self keyword is optional  endend...puts product.price_with_tax # 1838.85#class method and variable (use self keyword)def self.calc_tax(amount) @@count = 1endputs Product::calc_tax(1599.99)# Inheritanceclass Customer < Person  attr_accessor :number  def initialize(name, number)    super(name)    @number = number  endend
Enter fullscreen mode Exit fullscreen mode

File I/O

# Readtext = File.read('exemple.txt')# Read by lineslines = File.readlines("exemple.txt")lines.each do |line|  puts "Line: #{line}"end# WriteFile.write('exemple.txt', 'text to write...')File.open(index.html, w) do | file |   file.puts text to write end
Enter fullscreen mode Exit fullscreen mode

Errors/Exceptions Handling

begin  # Any exceptions here ex. 0 / 1  0 / 1 rescue  # ...will make this code to run  puts "Exception"  do_something()end# Exception objectbegin  0 / 1rescue ZeroDivisionError => e  puts e.class.name  puts e.messageend
Enter fullscreen mode Exit fullscreen mode

Original Link: https://dev.to/rickavmaniac/my-beloved-ruby-cheat-sheet-208o

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To