I'm very new to Ruby and learning the basics. I'm trying to figure out the maximum value in an array, the position of that value in the array and print it out. I ran into a strange problem that I'm hoping someone can help explain.
Here's my code:
highest_grocery = 0
#This loop will iterate over all the grocery expenditures to find the maximum
expenses["groceries"].length.times do |i|
if highest_grocery < expenses["groceries"][i]
highest_grocery = expenses["groceries"][i]
friend_num_grocery = i + 1
end
end
print "Friend #{friend_num_grocery} paid the most for groceries. With a total grocery bill of: $#{highest_grocery}"
When I run this, I get an error that says undefined local variable or method friend_num_grocery for main:Object.
I struggled with this for a while, but by chance I found that if I created the friend_num_grocery variable earlier, it would work fine, like this:
highest_grocery = 0
friend_num_grocery = 0
#This loop will iterate over all the grocery expenditures to find the maximum
expenses["groceries"].length.times do |i|
if highest_grocery < expenses["groceries"][i]
highest_grocery = expenses["groceries"][i]
friend_num_grocery = i + 1
end
end
print "Friend #{friend_num_grocery} paid the most for groceries. With a total grocery bill of: $#{highest_grocery}"
Does anyone know why the first one did not work, but the second one did? Thank you!
friend_num_grocerydefined in the first example? If you're intending it to be defined at the bottom of the loop, you'll need to look into "variable scoping". It's an extremely important concept to understand.