Declarative Keyword Paramaters for Ruby
rake test
todef explain(options={}) "the #{options[:the]} says #{options[:says]}" end
explain the: "pig", says: "oink" # => "the pig says oink" explain the: "frog", says: "ribbit" # => "the frog says ribbit"
def explain2(options={}) animal = options[:the] sound = options[:says] "the #{animal} says #{sound}" end
def explain3(options={}) animal = options.fetch(:the) { "cow" } sound = options.fetch(:says){ "moo" } "the #{animal} says #{sound}" end
explain3 # => "the cow says moo"
def explain4(*args) options = args.last.is_a?(Hash) ? args.pop : {} animal = args[0] || options.fetch(:the) { "cow" } sound = args[1] || options.fetch(:says){ "moo" } "the #{animal} says #{sound}" end
explain4 "horse", "neigh" # => "the horse says neigh" explain4 "duck", says: "quack" # => "the duck says quack" explain4 the: "donkey", :says => "hee-haw" # => "the donkey says hee-haw"
require 'keyword_params'
class BarnYard extend KeywordParams
keyword(:the) { "cow" } keyword(:says) { "moo" } def explain(animal, sound) "the #{animal} says #{sound}" end end
b = BarnYard.new
b.explain "horse", "neigh" # => "the horse says neigh" b.explain "duck", says: "quack" # => "the duck says quack" b.explain the: "donkey", :says => "hee-haw" # => "the donkey says hee-haw" b.explain the: "cat" # => "the cat says moo" b.explain # => "the cow says moo"