imedo Development Blog

there is no charge for awesomeness

The splat operator is so pretty

with 2 comments

While researching something I stumpled upon this excellent article by Peter Cooper 21 Ruby Tricks You Should Be Using In Your Own Code which also mentions the Splat Operator

The splat operator is a very interesting ruby construct that, if used with care, simplyfies code like the ternary operator to write Array#join

%w{this is a test}.join(", ")

a little different and shorter:

%w{this is a test} * ", " 

It’s a silly example, but you get the point.
More on the splat operator can be found at Plan A’s Article – Ruby idioms : The splat operator. or Nick Kallen’s blog post Ruby Pearls Vol.1- The Splat Operator

For an example application I’m currently writing, I needed a simple value-object that holds a few attributes for sending an email. Using this value-object I can have the form fields prepopulated with data, when returning to the form.

Heres the class:

class Htmlmail
  attr_accessor :subject, :text, :sender, :recipient

  def initialize(args = {})
    args.each{ |k,v| p "#{v}"; self.send("#{k}=", v) if self.respond_to?(k) }
  end

  def to_ary
    [sender, recipient, subject, text]
  end
end

when implementing the to_ary method (which returns an array), you can use the object like this, where email is a Htmlmail-object:

class Multipart < ActionMailer::Base

  def some_mail(email)
    sender, recipient, title, message = *email
    ...
  end

end

Popularity: 6% [?]

Written by tkadauke

June 25th, 2008 at 1:56 pm

Posted in Development

Tagged with , ,

2 Responses to 'The splat operator is so pretty'

Subscribe to comments with RSS

  1. Hi,

    I believe your exemple:
    %w{this is a test} * “, ”

    …doesn’t use the splat operator, but simply the method Array#*
    As per the pickaxe :

    * With an argument that responds to to_str, equivalent to arr.join(str).

    Simon

    25 Jun 08 at 1:56 pm

  2. Erm, your first example is not splat, it’s Array#*, a method call.

    raggi

    25 Jun 08 at 1:56 pm

Leave a Reply