Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Use built-in methods:
- num = 6
- # Less preferred
- p num % 2 == 0
- # Preferred by a Rubyist
- p num.even?
- people = ["Joey", "Bex", "Andrew"]
- # Less preferred
- p people[people.length - 1]
- # Preferred by a Rubyist
- p people[-1]
- p people.last
- Useful methods/enums:
- enums: #times, #all?, #none?, #one?, #any?, #each, #select, #map
- arrays: #flatten, #include?, #max, #min, #count, #first, #last
- strings: #split(""), #join(""), #length, #chars, #each_char, #each_char.with_index
- universal: #each_with_index
- Symbols:
- str = "hello" # the string
- sym = :hello # the symbol
- # Symbols are Immutable!!!
- Symbols as hash keys:
- my_bootcamp = { :name=>"App Academy", :color=>"red", :locations=>["NY", "SF", "ONLINE"] }
- p my_bootcamp # => {:name=>"App Academy", :color=>"red", :locations=>["NY", "SF", "ONLINE"]}
- p my_bootcamp[:color] #=> "red
- # shortcut:
- my_bootcamp = { name:"App Academy", color:"red", locations:["NY", "SF", "ONLINE"] }
- Default Parameters:
- # By default, num will have the value of 1
- def repeat(message, num=1)
- message * num
- end
- p repeat("hi") # => "hi"
- p repeat("hi", 3) # => "hihihi"
- Option Hashes:
- If you have a method that accepts a hash as an argument,
- you can omit the braces when passing in the hash:
- def method(hash)
- p hash # {"location"=>"SF", "color"=>"red", "size"=>100}
- end
- method({"location"=>"SF", "color"=>"red", "size"=>100})
- # this also works:
- method("location"=>"SF", "color"=>"red", "size"=>100)
- def modify_string(str, options={"upper"=>false, "repeats"=>1})
- str.upcase! if options["upper"]
- p str * options["repeats"]
- end
- modify_string("bye") # => "bye"
- modify_string("bye", "upper"=>true, "repeats"=>3) # => "BYEBYEBYE"
- Splat operator:
- We use it when we want an unspecified amount of args;
- They will be stored in an array
- def method(arg_1, arg_2, *other_args)
- p arg_1 # "a"
- p arg_2 # "b"
- p other_args # ["c", "d", "e"]
- end
- method("a", "b", "c", "d", "e")
- We can also use it if we want to unpack an array/hash:
- arr_1 = ["a", "b"]
- arr_2 = ["d", "e"]
- arr_3 = [ *arr_1, "c", *arr_2 ]
- p arr_3 # => ["a", "b", "c", "d", "e"]
- old_hash = { a: 1, b: 2 }
- new_hash = { **old_hash, c: 3 }
- p new_hash # => {:a=>1, :b=>2, :c=>3}
- Inject/reduce method:
- Each block of code executed in (el) will go to acc
- p [11, 7, 2, 4].inject { |acc, el| acc + el } # => 24
- p [11, 7, 2, 4].inject { |acc, el| acc * el } # => 616
- Swapping variables or elements of an array:
- array = ["a", "b", "c", "d"] # let's swap "a" and "b"
- array[0], array[1] = array[1], array[0]
- p array # => ["b", "a", "c", "d"]
- Scope:
- Blocks don't have their own scope, they are really a part of the containing method's scope.
- If's don't have their own scope too:
- if true
- drink = "cortado"
- end
- p drink
- Global Variables:
- Add '$' char before variable
- $message = "hello globe"
- def say_hello
- p $message
- end
- say_hello # => "hello globe"
- Ruby uses some by default: $PROGRAM_NAME, $stdin, $stdout
- Constants:
- # We create them by naming them in all caps, and we can't reassign them.
- # We can modify/mutate them though.
- FOOD = "pho"
- FOOD[0] = "P"
- p FOOD # => "Pho
- FOOD = "ramen" #warning: already initialized constant FOOD
- #warning: previous definition of FOOD was here
- RSPEC:
- Example RSPEC:
- # /spec/prime_spec.rb
- require "prime"
- describe "prime? method" do
- it "should accept a number as an argument" do
- expect { prime?(7) }.to_not raise_error
- end
- context "when the number is prime" do
- it "should return true" do
- expect(prime?(7)).to eq(true)
- expect(prime?(11)).to eq(true)
- expect(prime?(13)).to eq(true)
- end
- end
- context "when the number is not prime" do
- it "should return false" do
- expect(prime?(4)).to eq(false)
- expect(prime?(9)).to eq(false)
- expect(prime?(20)).to eq(false)
- expect(prime?(1)).to eq(false)
- end
- end
- end
- Exceptions:
- Once exception is reached, rescue block will execute, and program will continue
- You can also raise custom exceptions.
- "Raise" is how you bring up the exception, "Begin-rescue" is how you react to it
- def format_name(first, last)
- if !(first.instance_of?(String) && last.instance_of?(String))
- raise "arguments must be strings"
- end
- first.capitalize + " " + last.capitalize
- end
- first_name = 42
- last_name = true
- begin
- puts format_name(first_name, last_name)
- rescue
- # do stuff to rescue the "arguments must be strings" exception...
- puts "there was an exception :("
- end
- Blocks:
- They can be either one-liners or multiline
- [1,2,3].map { |num| -(num * 2) } # => [-2, -4, -6]
- Blocks can accept parameters if we name them between pipes (|param_1, param_2, etc.|).
- When blocks uses a single method:
- good:
- ["a", "b", "c"].map(&:upcase) #=> ["A", "B", "C"]
- [1, 2, 5].select(&:odd?) #=> [1, 5]
- bad:
- ["a", "b", "c"].map { |str| str.upcase } #=> ["A", "B", "C"]
- [1, 2, 5].select { |num| num.odd? } #=> [1, 5]
- We use & to convert this "method" into an object that we can pass into map.
- Procs:
- A proc is an object that contains a block.
- We need procs because they allow us to save blocks to variables so we can manipulate them in our code.
- doubler = Proc.new { |num| num * 2 }
- p doubler # #<Proc:0x00007f9a8b36b0c8>
- p doubler.call(5) # => 10
- p doubler.call(7) # => 14
- is_even = Proc.new do |num|
- if num % 2 == 0
- true
- else
- false
- end
- end
- p is_even.call(12) # => true
- Passing Proc to a method:
- # Version 1: manual, proc accepting method
- def add_and_proc(num_1, num_2, prc)
- sum = num_1 + num_2
- p prc.call(sum)
- end
- doubler = Proc.new { |num| num * 2 }
- add_and_proc(1, 4, doubler) # => 10
- # Version 2: automatic conversion from block to proc
- def add_and_proc(num_1, num_2, &prc)
- sum = num_1 + num_2
- p prc.call(sum)
- end
- add_and_proc(1, 4) { |num| num * 2 } # => 10
- def my_method(&prc)
- # ...
- end
- # By looking at the parameter `&prc` we know that my_method must be passed a block,
- # because & denotes conversion from block to proc here:
- my_method { "I'm a block" }
- "&" converts blocks into procs, and procs into blocks.
- If method has a (&prc) parameter - it needs a block
- If method has a (prc) parameter - it needs a proc!
- example:
- doubler = Proc.new { |num| num * 2 }
- [1,2,3].map(&doubler) # => [2, 4, 6]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement