Ruby Tips & Tricks

Igor Kasyanchuk
Dec 9, 2023 • 2 minutes read

Ruby

  • method(:s).source_location + .method(:s).source

    to determine where a method is defined as useful in the STI context Bundle.lastmethod(:weight_in_kg).source_location

    pry(main)> User.new.method(:full_name).source.display
      def full_name
        [first_name, last_name].compact.join(" ")
      end
    => nil
    
  • bundle open <gem name>

    bundle open devise (or any other gem) - opens gem source code in the default editor

  • object.methods

    Lists all methods of an object. You can do also something like:

    Object.methods - @user.methods

  • remember about Struct

    define object on the fly

    class Car < Struct.new(:wheels, :engine)
    end
    
    Car.new 
    => #<struct Car wheels=nil, engine=nil>
    
  • use _1 for blocks

    Example, instead of arrs.sum { |e| e.method }arrs.sum { _1.method }

  • memoization for a multi-line code

    @cached ||= begin
      a = 1
      b = 2
      a + b
    end
    
  • Array .dig method

    >> array = [1, 5, [7, 9, 11, ["Treasure"], "Sigma"]]
    => [1, 5, [7, 9, 11, ["Treasure"], "Sigma"]]
    >> array.dig(2, 3, 0)
    => "Treasure"
    
  • test your regexps

    go to https://rubular.com/

  • endless methods (define method in a single line)

    def double(num) = num * 2
      puts double(5) 
    # 10
    
  • .filter_map

    >> [1, 2, 3, 4, 5, 6, 7].filter_map { |x| x.odd? ? x.to_s : nil }
    => ["1", "3", "5", "7"]
    
  • Anonymous Class

    Classes can have no name, these class are called anonymous classes. Look at the example below, type it and execute it:

    # anonymous_class.rb
    person = Class.new do
      def say_hi
        'Hi'
      end
    end.new
    
    puts person.say_hi
    puts person.class
    
    # Output
    Hi
    #<Class:0x0000000002696840>
    
  • begin/rescue/else/ensure

    https://stackoverflow.com/questions/6279956/ruby-exceptions-why-else

  • multiline string with <<~MESSAGE

    def message_body
      <<~MESSAGE
      *New Freight Request:*
      *Merchant:* #{resource.merchant&.name}
      *Mode:* #{resource.transportation_mode.join(', ')}
      *Freight type:* #{resource.freight_type}
      *Origin:* #{resource.origin}
      *Destination:* #{resource.destination}
      *Cargo ready date:* #{resource.cargo_ready_date}
      *Additional note:* #{resource.additional_note}
      *Link to AA:* <#{Rails.application.config_for(:urls).base}/admin/scx_freight_requests/#{resource.id}>
      MESSAGE
    end
    

Useful gems

See all