条件分岐の構文としてRubyには「if-else」があります。

animal = 'hippopotamus'

if animal.size > 10
  puts "You must idiot!"
else
  puts "You are good in size."
end
# >> You must idiot!

しかし、たかがメッセージの出力にこんなに行数を消費したくはない、と思うのが平均的なRubyistの思考です。そしてRuby唯一の三項演算子を使います。

puts animal.size > 10 ? "You must idiot!" : "You are good in size."
# >> You must idiot!

短くなりましたが、もう一つ問題があります。それは、条件分岐はメソッドチェーンに載せづらいということです。

puts (animal.size > 10 ? "You must idiot!" : "You are good in size.").upcase
# >> YOU MUST IDIOT!

puts begin
  if animal.size > 10
    "You must idiot!"
  else
    "You are good in size."
  end
end.upcase
# >> YOU MUST IDIOT!

このように括弧やbegin-endで括るか一時変数に代入する必要があります。

そんなわけで...

こんなのどうですか?

module CoreExt
  refine Array do
    def [](*args)
      if args.size == 1 &&
         [true, false, nil].any? { |e| e == args.first }
        super( args.first ? 0 : 1 )
      else
        super
      end
    end
  end
end

using CoreExt

animal = 'hippopotamus'

puts ["You must idiot!", "You are good in size."][animal.size > 10].upcase
# >> YOU MUST IDIOT!

result = false
%w(success fail)[result] # => "fail"

つまりArray#[]を弄って、引数にtrueが渡されたらindex 0の要素を返し、falseなら1の要素を返すようにします。

みんな一度はこんなこと考えたんじゃないですかねー。でも、まあ..いらないですかね..


関連記事:

Rubyの条件分岐をメソッド化する



blog comments powered by Disqus
ruby_pack8

100円〜で好評発売中!
M'ELBORNE BOOKS