Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 6.76 KB | None | 0 0
  1. Use built-in methods:
  2.   num = 6
  3.   # Less preferred
  4.   p num % 2 == 0
  5.   # Preferred by a Rubyist
  6.   p num.even?
  7.   people = ["Joey", "Bex", "Andrew"]
  8.   # Less preferred
  9.   p people[people.length - 1]
  10.   # Preferred by a Rubyist
  11.   p people[-1]
  12.   p people.last
  13.  
  14. Useful methods/enums:
  15.   enums: #times, #all?, #none?, #one?, #any?, #each, #select, #map
  16.   arrays: #flatten, #include?, #max, #min, #count, #first, #last
  17.   strings: #split(""), #join(""), #length, #chars, #each_char, #each_char.with_index
  18.   universal: #each_with_index
  19.  
  20. Symbols:
  21.   str = "hello"   # the string
  22.   sym = :hello    # the symbol
  23.   # Symbols are Immutable!!!
  24.   Symbols as hash keys:
  25.     my_bootcamp = { :name=>"App Academy", :color=>"red", :locations=>["NY", "SF", "ONLINE"] }
  26.     p my_bootcamp           # => {:name=>"App Academy", :color=>"red", :locations=>["NY", "SF", "ONLINE"]}
  27.     p my_bootcamp[:color]   #=> "red
  28.     # shortcut:
  29.     my_bootcamp = { name:"App Academy", color:"red", locations:["NY", "SF", "ONLINE"] }
  30.  
  31. Default Parameters:
  32.   # By default, num will have the value of 1
  33.   def repeat(message, num=1)
  34.       message * num
  35.   end
  36.   p repeat("hi") # => "hi"
  37.   p repeat("hi", 3) # => "hihihi"
  38.  
  39. Option Hashes:
  40.   If you have a method that accepts a hash as an argument,
  41.   you can omit the braces when passing in the hash:
  42.   def method(hash)
  43.     p hash  # {"location"=>"SF", "color"=>"red", "size"=>100}
  44.   end
  45.  
  46.   method({"location"=>"SF", "color"=>"red", "size"=>100})
  47.   # this also works:
  48.   method("location"=>"SF", "color"=>"red", "size"=>100)
  49.  
  50.   def modify_string(str, options={"upper"=>false, "repeats"=>1})
  51.       str.upcase! if options["upper"]
  52.       p str * options["repeats"]
  53.   end
  54.  
  55.   modify_string("bye")   # => "bye"
  56.   modify_string("bye", "upper"=>true, "repeats"=>3)   # => "BYEBYEBYE"
  57.  
  58. Splat operator:
  59.   We use it when we want an unspecified amount of args;
  60.   They will be stored in an array
  61.   def method(arg_1, arg_2, *other_args)
  62.     p arg_1         # "a"
  63.     p arg_2         # "b"
  64.     p other_args    # ["c", "d", "e"]
  65.   end
  66.  
  67.   method("a", "b", "c", "d", "e")
  68.  
  69.   We can also use it if we want to unpack an array/hash:
  70.     arr_1 = ["a", "b"]
  71.     arr_2 = ["d", "e"]
  72.     arr_3 = [ *arr_1, "c", *arr_2 ]
  73.     p arr_3 # => ["a", "b", "c", "d", "e"]
  74.  
  75.     old_hash = { a: 1, b: 2 }
  76.     new_hash = { **old_hash, c: 3 }
  77.     p new_hash # => {:a=>1, :b=>2, :c=>3}
  78.  
  79.  
  80. Inject/reduce method:
  81.   Each block of code executed in (el) will go to acc  
  82.   p [11, 7, 2, 4].inject { |acc, el| acc + el } # => 24
  83.   p [11, 7, 2, 4].inject { |acc, el| acc * el } # => 616
  84.  
  85. Swapping  variables or elements of an array:
  86.   array = ["a", "b", "c", "d"]    # let's swap "a" and "b"
  87.   array[0], array[1] = array[1], array[0]
  88.   p array         # => ["b", "a", "c", "d"]
  89.  
  90. Scope:
  91.   Blocks don't have their own scope, they are really a part of the containing method's scope.
  92.   If's don't have their own scope too:
  93.     if true
  94.       drink = "cortado"
  95.     end
  96.     p drink
  97.    
  98.   Global Variables:
  99.     Add '$' char before variable
  100.     $message = "hello globe"
  101.     def say_hello
  102.         p $message
  103.     end
  104.     say_hello # => "hello globe"
  105.  
  106.     Ruby uses some by default: $PROGRAM_NAME, $stdin, $stdout
  107.  
  108.   Constants:
  109.     # We create them by naming them in all caps, and we can't reassign them.
  110.     # We can modify/mutate them though.
  111.     FOOD = "pho"
  112.     FOOD[0] = "P"
  113.     p FOOD # => "Pho
  114.  
  115.     FOOD = "ramen"  #warning: already initialized constant FOOD
  116.                     #warning: previous definition of FOOD was here
  117.  
  118. RSPEC:
  119.   Example RSPEC:
  120.     # /spec/prime_spec.rb
  121.     require "prime"
  122.  
  123.     describe "prime? method" do
  124.       it "should accept a number as an argument" do
  125.         expect { prime?(7) }.to_not raise_error
  126.       end
  127.  
  128.       context "when the number is prime" do
  129.         it "should return true" do
  130.           expect(prime?(7)).to eq(true)
  131.           expect(prime?(11)).to eq(true)
  132.           expect(prime?(13)).to eq(true)
  133.         end
  134.       end
  135.  
  136.       context "when the number is not prime" do
  137.         it "should return false" do
  138.           expect(prime?(4)).to eq(false)
  139.           expect(prime?(9)).to eq(false)
  140.           expect(prime?(20)).to eq(false)
  141.           expect(prime?(1)).to eq(false)
  142.         end
  143.       end
  144.     end
  145.  
  146. Exceptions:
  147.   Once exception is reached, rescue block will execute, and program will continue
  148.   You can also raise custom exceptions.
  149.   "Raise" is how you bring up the exception, "Begin-rescue" is how you react to it
  150.  
  151.     def format_name(first, last)
  152.       if !(first.instance_of?(String) && last.instance_of?(String))
  153.         raise "arguments must be strings"
  154.       end
  155.  
  156.       first.capitalize + " " + last.capitalize
  157.     end
  158.  
  159.     first_name = 42
  160.     last_name = true
  161.     begin
  162.       puts format_name(first_name, last_name)
  163.     rescue
  164.       # do stuff to rescue the "arguments must be strings" exception...
  165.       puts "there was an exception :("
  166.     end
  167.  
  168. Blocks:
  169.   They can be either one-liners or multiline
  170.     [1,2,3].map { |num| -(num * 2) } # => [-2, -4, -6]
  171.     Blocks can accept parameters if we name them between pipes (|param_1, param_2, etc.|).
  172.    
  173.     When blocks uses a single method:
  174.         good:
  175.             ["a", "b", "c"].map(&:upcase) #=> ["A", "B", "C"]
  176.             [1, 2, 5].select(&:odd?)      #=> [1, 5]
  177.         bad:
  178.             ["a", "b", "c"].map { |str| str.upcase }  #=> ["A", "B", "C"]
  179.             [1, 2, 5].select { |num| num.odd? }       #=> [1, 5]
  180.     We use & to convert this "method" into an object that we can pass into map.
  181.    
  182. Procs:
  183.     A proc is an object that contains a block.
  184.     We need procs because they allow us to save blocks to variables so we can manipulate them in our code.
  185.  
  186.     doubler = Proc.new { |num| num * 2 }
  187.     p doubler # #<Proc:0x00007f9a8b36b0c8>
  188.     p doubler.call(5) # => 10
  189.     p doubler.call(7) # => 14
  190.  
  191.     is_even = Proc.new do |num|
  192.   if num % 2 == 0
  193.             true
  194.         else
  195.             false
  196.   end
  197.     end
  198.     p is_even.call(12) # => true
  199.  
  200.     Passing Proc to a method:
  201.         # Version 1: manual, proc accepting method
  202.         def add_and_proc(num_1, num_2, prc)
  203.             sum = num_1 + num_2
  204.             p prc.call(sum)
  205.         end
  206.  
  207.         doubler = Proc.new { |num| num * 2 }
  208.         add_and_proc(1, 4, doubler)   # => 10
  209.  
  210.         # Version 2: automatic conversion from block to proc
  211.         def add_and_proc(num_1, num_2, &prc)
  212.             sum = num_1 + num_2
  213.             p prc.call(sum)
  214.         end
  215.  
  216.         add_and_proc(1, 4) { |num| num * 2 }  # => 10
  217.    
  218.  
  219.     def my_method(&prc)
  220.         # ...
  221.     end
  222.  
  223.     # By looking at the parameter `&prc` we know that my_method must be passed a block,
  224.     # because & denotes conversion from block to proc here:
  225.     my_method { "I'm a block" }
  226.  
  227.     "&" converts blocks into procs, and procs into blocks.
  228.     If method has a (&prc) parameter - it needs a block
  229.     If method has a (prc) parameter - it needs a proc!
  230.     example:
  231.         doubler = Proc.new { |num| num * 2 }
  232.         [1,2,3].map(&doubler) # => [2, 4, 6]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement