Ruby Language

Oct 8, 2021

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

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.