Ruby - Methods - Keyword Arguments

  • + 0 comments
    def convert_temp(temp, input_scale: String, output_scale: 'celsius')
      conversion = [
        input_scale.strip.downcase.to_sym,
        output_scale.strip.downcase.to_sym
      ]
      k_to_c = lambda { |k| k - 273.15 }
      c_to_k = lambda { |c| c + 273.15 }
      c_to_f = lambda { |c| (c * (9.0/5.0)) + 32.0 }
      f_to_c = lambda { |f| (f - 32.0) * (5.0/9.0) }
    
      case conversion
        when [:kelvin, :kelvin]
          temp
        when [:celsius, :celsius]
          temp
        when [:fahrenheit, :fahrenheit]
          temp
        when [:kelvin, :celsius]
          k_to_c.call(temp)
        when [:celsius, :kelvin]
          c_to_k.call(temp)
        when [:kelvin, :fahrenheit]
          c_to_f.call(k_to_c.call(temp))
        when [:fahrenheit, :kelvin]
          c_to_k.call(f_to_c.call(temp))
        when [:celsius, :fahrenheit]
          c_to_f.call(temp)
        when [:fahrenheit, :celsius]
          f_to_c.call(temp)
        else
          raise StandardError, "Invalid Units: #{input_scale} or #{output_scale}"
      end
    end