Ruby - Methods - Keyword Arguments

Sort by

recency

|

105 Discussions

|

  • + 0 comments

    Overall, keyword arguments in Ruby are excellent for making APIs and method calls more intuitive, especially when dealing with multiple or optional parameters. Winbuzz Com

  • + 0 comments

    def convert_temp(temp, input_scale="celsius", output_scale="celsius"): scales = { "celsius": (1, 0), "kelvin": (1, 273.15), "fahrenheit": (1.8, 32) }

    factor_in, offset_in = scales.get(input_scale, (1, 0))
    factor_out, offset_out = scales.get(output_scale, (1, 0))
    
    temp_celsius = (temp - offset_in) / factor_in
    
    result = (temp_celsius * factor_out) + offset_out
    
    return result
    

    end

  • + 0 comments

    "Ruby - Methods - Keyword Arguments" is a great topic because it touches on one of Ruby’s most readable and flexible features. Keyword arguments make method calls more expressive and self-documenting, which is especially helpful in larger or more complex codebases. Gold Site 365

  • + 1 comment

    I'm with a problem with my code, because it works when I run it on VScode, but when I try on HackerRank, it don't works

    def convert_temp(temperature,input_scale:,output_scale:'celsius') if input_scale=='celsius' if output_scale=='kelvin'

      temperature+=273.15
    
    elsif output_scale=='fahrenheit'
    
      temperature=((temperature*9/5)+32).to_f
    
    end
    

    elsif input_scale=='kelvin'

    if output_scale=='celsius'
    
      temperature-=273.15
    
    elsif output_scale=='fahrenheit'
    
      temperature=(((temperature-273.15)*9/5)+32).to_f
    
    end
    

    elsif input_scale=='fahrenheit'

    if output_scale=='celsius'
    
      temperature = ((temperature-32)*5/9).to_f
    
    elsif output_scale=='kelvin'
    
      temperature =(((temperature-32)*5/9)+273.15).to_f
    end
    

    end end

    puts convert_temp(0, input_scale: 'celsius', output_scale: 'kelvin')

  • + 0 comments

    Using Ruby Symbols and Lambdas to get a readable table of conversions.

    def convert_temp(temperature, input_scale:, output_scale: :celsius)    
        {
            [:celsius, :fahrenheit] => ->(t) { (t * 9.0/5.0) + 32.0 },
            [:celsius, :kelvin] => ->(t) { t + 273.15 },
            [:fahrenheit, :celsius] => ->(t) { (t - 32.0) * 5.0/9.0 },
            [:fahrenheit, :kelvin] => ->(t) { ((t - 32.0) * 5.0/9.0) + 273.15 },
            [:kelvin, :celsius] => ->(t) { t - 273.15 },
            [:kelvin, :fahrenheit] => ->(t) { (t - 273.15) * 9.0/5.0 + 32.0 },
        }[[input_scale.to_sym, output_scale.to_sym]].call(temperature)
    end