Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby

It's difficult to understand oneline if statement.

Hi,

  1. Could you explain the different the following 2 statements?

answer = answer.to_i if kind == "number" answer = (answer.to_i if kind == "number")

  1. Could you explain why the following statement is valid?

(answer.to_i if kind == "number")

Thanks Ross

2 Answers

Hi Ross!

The brackets are allowed when setting a variable in Ruby because they can be used for mathematical purposes like the following: (40 * 2) + (20+20).

In the example you have given it will just basically encase the statement and not make any difference.

I hope this helped you out!

Hi Luke,

Thanks for your answer, but the following statements are different

answer = answer.to_i if kind == "number" answer = (answer.to_i if kind == "number")

By the way, I want to know the reason why "(answer.to_i if kind == "number")" is valid. According to oneline if statement syntax, "(answer.to_i if kind == "number") " should be same as the following statement "if kind == "number" answer.to_i end" But it's wrong statement.

Thanks, Ross

Hi Luke,

Thanks for your answer, but the following statements are different

answer = answer.to_i if kind == "number" answer = (answer.to_i if kind == "number")

By the way, I want to know the reason why "(answer.to_i if kind == "number")" is valid. According to oneline if statement syntax, "(answer.to_i if kind == "number") " should be same as the following statement if kind == "number" answer.to_i end But it's wrong statements.

Thanks, Ross