4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyの多次元配列で最初の要素を加工して返したい(tap/break等について)

Last updated at Posted at 2015-02-08
問題 http://nabetani.sakura.ne.jp/hena/ord28spirwa/
シミュレーション (Python/Ruby/C++) http://qiita.com/cielavenir/items/8c77a158136bd668a27b
規則性 (Python/Ruby/C/C#/Java) http://qiita.com/cielavenir/items/a285b0cea4a26ff886b8
規則性 (D/Go/Swift/PHP/ Vala ) http://qiita.com/cielavenir/items/edb1daff9ea861a418ec
規則性 (VB/F#/Perl) http://qiita.com/cielavenir/items/0c84af4049ab161f82c1
規則性 (PowerShell) http://qiita.com/cielavenir/items/d9ef9f12068e99e888f2
規則性 ( AIR-lang ) http://qiita.com/cielavenir/items/d804f61412fb4f07ba06
規則性 (Crystal/Perl6) http://qiita.com/cielavenir/items/13896a662b05da8b77a2
Rubyの多次元配列で最初の要素を加工して返したい
(tap/break等について)
http://qiita.com/cielavenir/items/3f209351b924e2615f5e
  • ※※※ こちらは、答案のディスカッションで出たネタとなります。 ※※※

「配列coordinatesの最初の要素を、その第一要素に1、第二要素に2を足して返す」という問題を考える。
この問題には複数のアプローチが存在する。

  • 普通に1要素ずつ取る
    • 最も移植性が高い
    • タイプが冗長になる
[coordinates[0]+1,coordinates[1]+2]
  • 足す数を配列として持ち、混成する
    • ある程度読みやすく、変数名変更に対してロバスト
    • [[0,-1],[0,1],[-1,0],[1,0]][0]みたいなのに強い
coordinates[0].zip([1,2]).map{|e|e.reduce(:+)}
  • tap/break
    • break値がtapの返し値になることを利用
    • 慣れていないと読みにくい
coordinates.tap{|e|break [e[0]+1,e[1]+2]}
  • find_yield ergo
    • 多分一番直感的
    • facets gemが必要になってしまう
    • 案1〜3と異なり、boolean_array.find_yield{|e|!e}とすると誤作動する。boolean_arrayは多次元配列ではないのでfind_yieldを使おうと思う人はいないと思いますが。ちなみに数値についてはRubyだと0は真なので大丈夫。
coordinates.ergo{|e|[e[0]+1,e[1]+2]}
coordinates.yield_self{|e|[e[0]+1,e[1]+2]}

案3で解いている人がいたので。tap/breakの使い方を知った。
勉強会会場では誤って案1をお薦めしてしまったが、案2にするべきだった--;;

4
4
1

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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?