Home > Net >  Ruby - Code repeating methods when not wanting them to repeat
Ruby - Code repeating methods when not wanting them to repeat

Time:11-18

I'm trying to understand why this code is repeating the age and name methods 2 times. When i run the code, it asks for the age and the name, but, it then asks for the name and age again. Im not sure what exactly i've done wrong here? its only meant to ask 1 time.

I tried global variables and it worked but i dont really want to use global variables

require 'date'


def get_age()
  puts("Enter your age in years: ")
  age = gets.to_i()
  return age
end


def get_string()
  puts("Enter your name: ")
  s = gets.chomp()
  return s
end


def print_year_born(get_age)
  year_born = Date.today.year - get_age
  puts(get_string   "\sYou were born in: "   year_born.to_s)
end

def main()
  get_age()
  get_string()
  print_year_born(get_age)
end

main()

what am i missing?

CodePudding user response:

It's called twice because you call it twice. On line 1 of main, you call get_age() and discard the value it returns. Then on line 3 you call print_year_born(get_age) which invokes get_age again, but this time passes the value returned to print_year_born.

You seem to have some confusion over how methods work. Every time you type get_age, you're calling the method. You don't have to call the methods by themselves on lines 1 and 2, those bare invocations (get_age()/get_string()) are completely redundant. They call the methods but do absolutely nothing with the value they returns.

It's not clear what purpose do you think the first two lines in main serve, but you should remove them:

def main()
  get_age()    # Wrong: call get_age and ignore return value. Why?
  get_string() # Wrong: call get_string and ignore return value. Why? 
  
  # Correct: call get_age and use the return value as an argument to print_year_born
  print_year_born(get_age)
end
  •  Tags:  
  • ruby
  • Related