1
1

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でjavascriptみたいな関数渡しをする小技

Last updated at Posted at 2016-09-08

はじめに

railsで作業してて、以下のように配列をmapして別のメソッドに通した値を使いたいケースがありました

localized_column_names = Product.column_names.map { |column_name|
  Product.human_attribute_name(column_name)
}

こんな場合javascriptなら関数を渡せて簡潔なのにな、と思ったのです。
以下のように

const localizedColumnNames = Product.columnNames.map(Product.humanAttributeName);

rubyでやる場合はMethodオブジェクトで代用

メソッドをMethodオブジェクトで渡せば可能なようです

localized_column_names = Product.column_names.map(&Product.method(:human_attribute_name))

オブジェクトを do...end のブロックのように解釈させるには頭に & を付けて引数として与えればOKです。
こうすると内部的に #to_proc が呼ばれるのかな?

まぁまぁ簡潔になりましたね

1
1
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?