Map

  • Map transfrom data from Arrays, Hashes & Ranges.
  • Map returns a new array with the results. To to change the original array use map!

Map basic

["a", "b", "c"].map { |string| string.upcase }

Map With Index

["a", "b", "c"].map.with_index { |char, index| [ch, index] }

Map With Index NOT Start from 0

["a", "b", "c"].map.with_index(1) { |char, index| [ch, index] }

Map Shorthand &:

["1", "2", "3"].map(&:to_i)

["cat", "dog", "fish"].map(&:class)

Map from Hash

hash = {
  name: 'Matz',
  language: 'Ruby'
}

hash.map { |key, value| [key, value.to_sym] }.to_h

Uniq

[1, 1, 1, 1, 2, 3].uniq # => [1, 2, 3]

Use uniq! to change array.

nil? and friends

nil?

  • Only return true only for nil
nil.nil? # => true
false.nil? # => false
0.nil? # => false
"".nil? # => false

empty?

[].empty? # => true
"".empty? # => true
" ".empty? # => false

blank?

nil.blank? # => true
false.blank? # => true
[].blank? # => true
{}.blank? # => true
"".blank? # => true
"       ".blank? # => true
5.blank? # => false
0.blank? # => false

present?

Negatives of blank?

!blank? == present? #=> true

Misc

Random number

[*1..100].sample

Meta Programming Define Methods

class MyClass
  1.upto(1000) do |n|
    define_method :"method_#{n}" do
      puts "I am method #{n}!"
    end
  end
end

####

def get_bearer_token
  pattern = /^Bearer/
  header = request.authorization
  header = request.env['Authorization'] if header.blank?
  header.gsub(pattern, '').strip if header && header.match(pattern)
end
This site uses cookies to personalize content. Learn more.