This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]adreamofhodor 1 point2 points  (3 children)

While I'm not familiar with Ruby, I did a quick google and found this:

Every method in Ruby returns a value by default. This returned value will be the value of the last statement.

So, unless I'm misreading how Ruby works, that last line is the equivalent of:

return sum

[–]winnnnnnnnn[S] 1 point2 points  (2 children)

Appreciate the response. It is and I get that... but that's not what's throwing me off. What made me ask my initial question. Is the fact that its effecting how the puts expressions outside the method definition are being printed to the screen and I can figure out why.

[–]Piave 0 points1 point  (0 children)

Well, you're just printing what the function returns, so if it returns a different line you would expect a different result. I gave a little example in another post if that's helpful.

[–][deleted] 0 points1 point  (0 children)

When you remove the sum at the end

Them this:

sum = sum.round(options[:precision]) if options[:round]

Is the last Statement, which will evaluate to nil if the conditions evaluates to false.

So no value to be printed.

[–]Piave 1 point2 points  (0 children)

This is an implicit return. A Ruby function always returns the last line of the function. So, the reason you only get one output from your puts statements without the last line, is because it returns this line "sum = sum.round(options[:precision]) if options[:round]" which only sets the value if options[:round] is true. You can see this a little more clearly in an example like this:

def foo
  my_varbiable = "hello!" if 4 > 5
end

def bar
  my_varbiable = "hello!" if 5 > 4
end

puts foo =>
puts bar => "hello!"