哈希和符号

时间:2016-06-02 06:54:44

标签: ruby-on-rails ruby-on-rails-4

您好我想澄清一下我对铁轨中的哈希和符号的理解。

请说明这句话中的哈希和符号是什么?

<%= link_to image_tag(product.image_url), line_items_path(product_id:
product), method: :post %>

2 个答案:

答案 0 :(得分:3)

您的代码中涉及两个哈希值:

{ product_id: product } # 1
{ method: :post }       # 2 - can also be rewritten as { :method => :post }

在某些情况下,可以省略花括号(这是您在示例中所做的)。

还涉及3个符号:

:product_id # 1
:method     # 2
:post       # 3

哈希是数据结构,而符号是数据类型。

答案 1 :(得分:2)

line_items_path(product_id: product)

{product_id: product}是以缩写格式表示的哈希。传统格式为{:product_id => product}

:product_id是一个符号,您可以通过前面的冒号告诉它。在散列中使用时,可以使用product_id: product

之类的尾随冒号

通常标识哈希的花括号在作为方法的最后一个(或唯一)参数传递时是可选的。 Ruby解释器可以识别键/值对并假设它是一个哈希值。如果你把它们包括在内,它们看起来就像......

line_items_path( {product_id: product} )

或旧格式

line_items_path( {:product_id => product} )

同样,method: :post是一个哈希...在这种情况下,键和值都是符号,传统上表示为{:method => :post}

相关问题