Tips and Tricks

Single line if statement

condition ? if_true : if_false

Models

Class Methods

class SomeModel < ApplicationRecord
  def self.my_method(param_1)
    return 'my value'
  end
end

Default value for methods

def my_method(param_1 = 'some value')
  return "Value of the method is #{param_1}"
end

String

String conversion types

'CamelCasedName'.underscroe
# => "camel_cased_name"

'camel cased name'.titleize
# => "Camel Cased Name"

'camel cased name'.camelcase
# => "Camel cased name"

Arrays

Sorting an array

Person = Struct.new(:fname, :lname)
p1 = Person.new("John", "Doe")
p2 = Person.new("Jane", "Doe")
p3 = Person.new("Marry", "Mackan")
p4 = Person.new("John", "Beck")
[p1, p2, p3, p4].sort_by { |p| [p.fname, p.lname] }

Find index in an array

a = [1, 2, 5, 10]
a.find_index(5)
# => 2

Find a random object in an array

a = [1, 2, 5, 10]
a.sample
# => 2

Mapping values in an array

Maps always returns a new array

Example of doubling values in an array

array = [1,2,3]
array.map { |n| n * 2 }
# [2, 4, 6]

Ruby Language