Archive for the ‘idiom’ tag
The splat operator is so pretty
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% [?]
