How to call a script with arguments?

Asked

Viewed 278 times

3

I’m a little overweight, and researching on Physical Fitness, I figured out how to calculate my caloric expenditure, through the heartbeat.

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 expended_caloric.Rb
412.19956978967497

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

ruby gasto_caloric 150 70 20 30 m

How can I do that?

1 answer

3


You can "capture" parameters per 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 for other functionalities.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.