How to call a script with arguments?

2

I'm a little overweight, and searching on Physical Fitness , I figured out how to calculate my caloric expenditure through heart rate.

So I created the following script:

bpm = 150
massa = 70
idade = 20 # hahaha
tempo = 30
sexo = 'm'

def calcular(bpm, massa, idade, tempo, sexo)
  if sexo == 'm'
    ((-55.0969 + (0.6309 * bpm) + (0.1988 * massa) + (0.2017 * idade)) / 4.184) * tempo
  elsif sexo == 'f'
    ((-20.4022 + (0.4472 * bpm) - (0.1263 * massa) + (0.074 * idade)) / 4.184) * tempo
  end
end

p calcular(bpm, massa, idade, tempo, sexo)
  

Execution:
  ruby gasto_calorico.rb
  412.19956978967497

I would like to delete the definition of variables, and call the script as follows:

  

ruby ruby_caloric 150 70 20 30 m

How can I do this?

    
asked by anonymous 24.06.2017 / 01:17

1 answer

3

You can "catch" parameters by command line through the constant ARGV .

When you call ruby gasto_calorico 150 70 20 30 m , do:

unless ARGV.length == 5 #se os parametros não foram passados corretamente
  puts "Uso: ruby gasto_calorico -bpm -massa -idade -tempo -sexo"
  exit
end
params = ["bpm", "massa", "idade", "tempo", "sexo"]

#iteração do array ARGV
for i in (0...ARGV.length)
  puts params[i] + " => " + ARGV[i]
end 

The class GetoptLong automates this work for you and gives you other features.

    
24.06.2017 / 17:39