1

Trying to learn Ruby I ran into this kind of syntax.... Can anyone explain me what it means?

a = nil if b.nonzero?

nonzero? : Returns self if num is not zero, nil otherwise.

And thus does not return a boolean

3
  • nil is falsy value, so if b is nonzero, the if condition will evaluate to equivalent to false. Returns self means the value of b will be returned if its non-zero Commented Dec 18, 2015 at 12:21
  • You can use non-boolean values in conditions in Ruby. Commented Dec 18, 2015 at 12:21
  • Your question is unclear. What specific part of the syntax are you talking about that is unknown to you? There are 5 different syntax elements in the code you posted: an assignment to a local variable, the literal nil, the modifier conditional if, a local variable dereference and a method call. Which one is unknown to you? Commented Dec 18, 2015 at 12:58

1 Answer 1

3

Values in ruby are truthy and falsey. That is, if a value is not nil, or false, it is true. So if you have a function that returns 1, you can use that in a boolean expression some_function && true would resolve true.

Likewise, if it returned nil, some_function && true would return false.

There's a detailed and in depth explanation here: https://gist.github.com/jfarmer/2647362

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.