• Ruby to_i

    .to_i is frequently used to convert a string value to an integer. This method has a couple tricks up it’s sleeve. And if all the tricks fail, it returns zero instead of an exception.

    last_order = "10"
    next_order_number = last_order.to_i + 1
    
    address = "10B".to_i # returns 10
    distance = "100km".to_i # returns 100
    
    invoice_number = "ooops".to_i # returns 0
    

    However, the alternative way to convert to integer, Integer isn’t quite so easy going. But it has some tricks too; it can take base as argument.

    address = Integer("10B") # ArgumentError (invalid value for Integer(): "10B")
    Integer('111',2) # returns 7, as 2 indicates base 2
    Integer('0x100') # returns 256
    '0x100'.to_i # returns 0
    

    04 Apr 2020
  • Why Ruby Methods Return 'nil'

    In Ruby, the return keyword stops the execution flow of a method. It’s commonly used with guard clauses, which are a conditional statement at the top of a function.

    def currency(minor_currency)
      return "0.00" unless minor_currency.class == Integer
      major_currency = minor_currency / 100.to_f
      '%.2f' % major_currency
    end
    
    currency(1999) # 19.99
    

    The return keyword specifies the object to be returned to the caller when the method has done its work.

    If no return keyword is specified, the object created by the last line in the method is automatically treated as the return value. A method must always return exactly one object.

    Calling return without specifying an object to return results in a nil, which is returned by default.

    references

    https://www.thechrisoshow.com/2009/02/16/using-guard-clauses-in-your-ruby-code/

    29 Mar 2020
  • Ruby to_s

    It’s not uncommon to use .to_s in Ruby to cast a number to string.
    It’s also a way to take an API response in a hash and log it safely.

    String interpolation in Ruby also calls .to_s – automatically.

    person = {:name => 'Juanita', 
              :salary => 200000, 
              :title => 'Senior Software Engineer'}
    person.to_s
    # "{:name=>\"Juanita\", :salary=>200000, :title=>\"Senior Software Engineer\"}"
    "#{person}"
    # "{:name=>\"Juanita\", :salary=>200000, :title=>\"Senior Software Engineer\"}"
    

    22 Mar 2020