Syntax

Posts tagged with "Syntax."
  • 3

    OCT
    2008

    I'm Addicted to the Word Array

    Continuing with my recent trend of showing of fun uses of Ruby syntax, I have a confession to make: I'm addicted to Ruby's "word Array." I really am.

    I suspect most of you know this, but the word Array is a shortcut that can lessen the quote-comma-quote syndrome of simple a simple Array like:

    ["a", "wordy", "Array"]
    

    You can create the same Array with the word Array syntax:

    %w[a wordy Array]
    

    That's essentially just a String that will automatically be split() on whitespace to build an Array. You can use any amount of space any place you like, so you can layout the data in whatever way makes the most sense for you:

    require "pp"
    pp %w[ one   two   three
           four  five  six
           seven eight nine
                 zero        ]
    # >> ["one",
    # >>  "two",
    # >>  "three",
    # >>  "four",
    # >>  "five",
    # >>  "six",
    # >>  "seven",
    # >>  "eight",
    # >>  "nine",
    # >>  "zero"]
    

    Note that you can chose the punctuation characters used at either ends of the Array, some of which are paired while others just repeat:

    Read more…

  • 2

    OCT
    2008

    Interpolation and Statements

    I still cringe anytime I see code like:

    "1 + 2 = " + (1 + 2).to_s  # => "1 + 2 = 3"
    

    Some books even advocate the above, which is a real shame for Ruby.

    I imagine most of you know that you can rewrite the above to use String interpolation:

    "1 + 2 = #{1 + 2}"  # => "1 + 2 = 3"
    

    Let's think about that simple code a little bit more than we usually do though. What's really going on here? Obviously #{ … } inserts the result of the embedded code in the String, but it's important to realize that it also calls to_s() on that result to make it fit in the String.

    We can really make use of that knowledge if we try. Here's an example:

    Name = Struct.new(:first, :last) do
      def full
        "#{first} #{last}".strip  # trick 1
      end
      alias_method :to_s, :full   # trick 2
    end
    
    Name.new("James").full                     # => "James"
    Name.new(:James, :Gray).full               # => "James Gray"
    "My name is #{Name.new('James', 'Gray')}." # => "My name is James Gray."
    

    I've built a trivial data class for managing names here. In that, I've tried to make use of interpolation to the fullest.

    Read more…

    In: Ruby Voodoo | Tags: Syntax | 7 Comments
  • 2

    OCT
    2008

    Working With Multiline Strings

    I imagine most Rubyists are aware that Ruby has "heredocs," but do you really know all they can do? Let's find out.

    A "here document" is a literal syntax for a multiline String. In the most basic form, they look like this:

    p <<END_HEREDOC
    This is a
      multiline,
    as is String!
    END_HEREDOC
    # >> "This is a\n  multiline,\nas is String!\n"
    

    The <<NAME syntax introduces the heredoc, but it actually begins at the start of the following line. It continues until NAME occurs again, at the beginning of a line. Note the trailing newline in the example above. All of the data between start and finish is packaged up into a String and dropped in where the original <<NAME designator appeared.

    There are some important details in that description, namely that the String begins on the next line and that it's inserted where the heredoc was started. This means that the rest of the line where the heredoc is started can have normal Ruby code (though your editor may syntax highlight it badly):

    p <<END_SQL.gsub(/\s+/, " ").strip
    SELECT * FROM     users
             ORDER BY users.id DESC
    END_SQL
    # >> "SELECT * FROM users ORDER BY users.id DESC"
    

    Read more…

  • 13

    JUN
    2006

    Do I Need (These Parentheses()?)

    If you came to Ruby via the Learn to Program book or just don't yet have a consistent set of rules for when you do and don't need parentheses in Ruby code, this post is for you.

    I have nothing against Learn to Program, just to be clear. A member of my family is learning Ruby from it and it's going pretty well. I recommend it. However, Chris is a little inconsistent with his use of parentheses in the code samples, and worse, he doesn't really give you a good set of rules to decide when to make the choice. No problem. Let me give you the rules.

    I'm a chess player. In learning chess, you really go through two phases. First, you learn the rules of strategy. These will make you good because the rules are designed to help you avoid common mistakes. Now, to get great, you go through the second phase: learning when to break the strategy rules. Ruby is exactly the same.

    Here's the only rule of strategy you need to learn to get good: methods need parentheses around their arguments.

    Read more…