LoginSignup
2
2

More than 5 years have passed since last update.

Rubyのe-ラーニング研修システム ミニツク演習2について

Last updated at Posted at 2015-09-19

ミニツクの演習コース模範解答がRuby1.8以前のものでRuby1.9以降に対応していないので、自分なりに最新のRubyに対応した模範解答を考えてみた。
ちなみに問題は以下のようなもの

出題

コード例で呼び出しているclever_printメソッドを定義しましょう。clever_printメソッドのおこなう処理は、コメントアウトされている出力例から推測してください。

clever_print(["Ruby"], "the", ["Programming", "Language"])
 #=> Ruby the Programming Language  
 clever_print(["Agile", "Web", "Development"], "with", { :Rails => 3.0 })
 #=> Agile Web Development with Rails 3.0

ミニツク - Rubyのe-ラーニング研修システム

元々の模範解答は、

def clever_print(*args)
   converted = []
   args.each { |arg| converted << arg.to_a } #問題はココ!
   puts converted.join(" ")
end

なんだけど、 問題は"to_a"メソッド。Ruby1.9以降ではStringクラスからto_aメソッドが排除されているので、上の例だとno method errorになる。
なので、String型を判別して条件分岐させ、

def clever_print(*args)
  converted = []
  args.each { |arg|
    converted << (arg.is_a?(String) ? arg : arg.to_a)
  }
  puts converted.join(" ")
end

みたいにするのが一番シンプルかなー。もっとクレバーな方法があったら教えてください・・・

2
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2