Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRoss Peace
Courses Plus Student 17,401 PointsIt's difficult to understand oneline if statement.
Hi,
- Could you explain the different the following 2 statements?
answer = answer.to_i if kind == "number" answer = (answer.to_i if kind == "number")
- Could you explain why the following statement is valid?
(answer.to_i if kind == "number")
Thanks Ross
2 Answers
Luke Glazebrook
13,564 PointsHi 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!
Ross Peace
Courses Plus Student 17,401 PointsHi 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
Ross Peace
Courses Plus Student 17,401 PointsRoss Peace
Courses Plus Student 17,401 PointsHi 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