--0016e64cb1ea22342a04a00f8bbe
Content-Type: text/plain; charset=ISO-8859-1

On Sun, Apr 3, 2011 at 9:58 PM, wolf volpi <wolf_volpi / yahoo.com> wrote:

> What does the pipe in this example do?
>
>  @first_name  first_name || ''
>
> According to the text book that this example came from, the code ensures
> that an instance variable is not nil.  If @first_ name is nil, @first_
> name is set to the empty string.
>
> Thank you.
>
> --
> Posted via http://www.ruby-forum.com/.
>
>
1) In Ruby, false and nil are treated as falsy. Everything else is treated
as truthy.

"truthy" if nil         # nil
"truthy" if false       # nil
"truthy" if true        # "truthy"
"truthy" if "str"       # "truthy"
"truthy" if 1           # "truthy"
"truthy" if 1.23        # "truthy"
"truthy" if /regex/     # nil
"truthy" if :symbol     # "truthy"
"truthy" if 'r'..'ange' # "truthy"


2) Boolean operators return the objects themselves. In an "or" (double
pipes), if the first value is falsy, the second value is returned. If the
first value is truthy, it is returned.

nil   || "b"    # "b"
false || "b"    # "b"
"a"   || nil    # "a"
"a"   || false  # "a"
"a"   || "b"    # "a"
nil   || nil    # nil
nil   || false  # false
false || nil    # nil
false || false  # false

3) For some reason that I don't know (probably interpreter magic) an
uninitialized variable can be referenced in a boolean equation and it will
evaluate to nil.

first_name  irst_name || "" # ""
first_name  josh"
first_name  irst_name || "" # "josh"


So, it will set the variable to the empty string, if the variable is
undeclared, or false , or nil.

--0016e64cb1ea22342a04a00f8bbe--