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 trial

Ruby Ruby Loops Build a Simple Contact List Part 1: Asking Questions

Difficulty understanding the if statement after assignment to answer variable

I'm having a tough time understanding why the is statement if placed after the assignment to the answer variable rather than before. Traditionally the conditional comes before the code, is this just some of Ruby's syntactic sugar?

What's the difference between:

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

and:

if kind == "number" { answer = answer.to_i }

2 Answers

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

This is just Ruby's way of making things easier in some cases ;). If you have a simple condition with one line of code to execute, Ruby allows you to write it in one line without any end or curly braces, just like you wrote:

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

And yes, this is exactly the same thing as

if kind == "number" { answer = answer.to_i }

and this:

if kind == "number" 
  answer = answer.to_i
end

But notice that you need more characters in the second one. Same works for unless.

jason needs to understand that this hasn't been introduced in previous lessons so he needs to explain it. at least tell folks it's a new syntax and then give them links below the video for further reading if he doesn't want to explain it in the video. have a little sympathy for first time learners. not everything is intuitive to everybody. smh.