A little Ruby help

63 views
Skip to first unread message

Mark H

unread,
Jul 29, 2012, 11:46:20 AM7/29/12
to rubym...@googlegroups.com
I see the construct below in many of the RubyMotion samples & open source code.  Can anyone explain what is going on here.  Does this assign a block to an instance variable?  If that's the case, then every time the instance variable is referenced does the block execute?


  def fonts
    @fonts ||= begin
      UIFont.familyNames.sort.map do |family|
        fonts = UIFont.fontNamesForFamilyName(family).sort
        {:family => family, :fonts => fonts}
      end
    end
  end


Alan deLevie

unread,
Jul 29, 2012, 11:57:30 AM7/29/12
to rubym...@googlegroups.com
The "||=" (instead of just "=") means it's memoizing--a fancy word for "if the variable is false, assign it this value. Otherwise, don't do anything." 

Mark H

unread,
Jul 29, 2012, 12:04:07 PM7/29/12
to rubym...@googlegroups.com
Thanks!  I was confused by the "||=", thanks for explaining it.  I have the Pickaxe book, but cannot find an explanation for "||=" anywhere in the book.

Bruce Hobbs

unread,
Jul 29, 2012, 5:48:15 PM7/29/12
to rubym...@googlegroups.com
On Jul 29, 2012, at 9:04 AM, Mark H <meh...@gmail.com> wrote:

I have the Pickaxe book, but cannot find an explanation for "||=" anywhere in the book.

The index entry on page 812 points to section 9.4, "Conditional Execution," on page 126. The discussion begins at the bottom of that page.
--
Bruce Hobbs           856 N Monterey St     Alhambra, CA 91801-1574       
Home:  626-570-8028   Cell:  626-278-0273   FAX:  208-474-0732

Ben Taylor

unread,
Jul 29, 2012, 9:02:41 PM7/29/12
to rubym...@googlegroups.com
To understand better how this construct works, try writing in irb

>> nil || "steve"
>> "steve" || "john"
>> "steve" || nil

>> nil && "steve"
>> "steve" && nil
>> "steve" && "john"

The construct ||= is shorthand for
>> @blah = @blah || "something"

It's common practice in many programming languages to use boolean operators like this as shorthand for using an if statement.

>> @blah ||= "something"

Can also be written as

>> @blah = "something" unless @blah

In more verbose languages it would need to be a full if statement.

Bruce Hobbs

unread,
Jul 30, 2012, 1:15:20 PM7/30/12
to rubym...@googlegroups.com
On Jul 29, 2012, at 6:02 PM, Ben Taylor <m...@taybenlor.com> wrote:

The construct ||= is shorthand for
>> @blah = @blah || "something"

Not that it's a big difference, but in the "Magic Defined" section of the article "Even More Eloquent Ruby" <http://subinterest.com/rubies-in-the-rough/5-even-more-eloquent-ruby> from his unfortunately short-lived newsletter Rubies in the Rough, James Edward Gray III turned on Ruby warnings to demonstrate that it's actually closer to

@blah = (defined?(@blah) && @blah) || "something"
Reply all
Reply to author
Forward
0 new messages