LoginSignup
7
6

More than 5 years have passed since last update.

引数の最後の引数が「裸のHash(Bare hash)」

Last updated at Posted at 2016-01-18
content_tag :span, "Hello", id: "foo", class: "bar"

のように、ハッシュの要素を引数にいくつも並べて書ける理由をきちんと理解していなかった。

Ruby は、メソッドの最後の引数がハッシュリテラルなら、ハッシュリテラルを囲む {} を省略できるようにしている。これは裸のハッシュ(bare hash)と呼ばれることがあり、別々の名前付き引数を渡しているような見かけになる。
(「プログラミング言語 Ruby」を改変・強調して引用)

なるほど。

つまり

content_tag :span, "Hello", { id: "foo", class: "bar" }

のシンタックスシュガーである、ということ。

該当のソースコードはこうなっている。

def content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)
  if block_given?
    options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash)
    content_tag_string(name, capture(&block), options, escape)
  else
    content_tag_string(name, content_or_options_with_block, options, escape)
  end
end

ついでに、 Symbol にはハイフンを含むことが出来ないので

<div hidden-area="true"></div>

content_tag :div, "hello", "hidden-area": "true"

のように、キーを引用符で囲まないとシンタックスエラーになる。

なお、ハッシュの

key: value

表記は Ruby 1.9 から可能になったが、引用符 + ":" が可能になったのは 2.2 から。

したがって、1.9以上2.2未満のバージョンの場合は、

content_tag :div, "hello", :"hidden-area" => "true", class: "foo"

になる。「そこだけは旧表記」ということ。

7
6
2

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