为什么每个语句中的变量顺序会影响输出?
Why order of variables inside each statement affects output?
在rails中,当我在each
语句中切换两个变量的顺序时有什么区别:
flash.each do |name, msg|
content_tag :div, msg, class: "alert alert-info"
#output => "Successfully updated item"
比较:
flash.each do |msg, name|
content_tag :div, msg, class: "alert alert-info"
#output => notice
当然在我的 item_controller
我有这个:
def update
if @item.update(item_params)
redirect_to @item, notice: "Successfully updated items"
else
render 'edit'
end
end
在你的例子中,你正试图从 flash var 中获取信息,他的定义如下:
flash = {
notice: "Successfully updated items"
}
每个语句都使用键值对来获取和操作哈希。
flash.each do |key, value|
#doSomething
end
在这种情况下,键是 "notice",值是 "Successfully updated items"。
在这种情况下,flash
是一个散列 http://docs.ruby-lang.org/en/2.0.0/Hash.html,这意味着有 keys
和 values
像字典一样存储。它与您可能习惯使用的常规变量有点不同。为了帮助您理解这个概念,您可以将散列内部的键视为子变量。当您使用 .each
之类的东西遍历哈希时,您将始终首先获得键,然后是值,键永远不会是 nil
但值可能是
例子
def update
if @item.update(item_params)
# This line is saying redirect and add a key, value to the
# flash hash, with the key being 'notice' and the 'value'
# "Successfully updated items"
redirect_to @item, notice: "Successfully updated items"
else
render 'edit'
end
end
你在上面问了一个问题,如果你只有一个变量,它是键还是值。它也不会是它只是一个变量。
例子
str = 'Hello'
content_tag :div, str, class: "alert alert-info"
#output => "Hello"
在rails中,当我在each
语句中切换两个变量的顺序时有什么区别:
flash.each do |name, msg|
content_tag :div, msg, class: "alert alert-info"
#output => "Successfully updated item"
比较:
flash.each do |msg, name|
content_tag :div, msg, class: "alert alert-info"
#output => notice
当然在我的 item_controller
我有这个:
def update
if @item.update(item_params)
redirect_to @item, notice: "Successfully updated items"
else
render 'edit'
end
end
在你的例子中,你正试图从 flash var 中获取信息,他的定义如下:
flash = {
notice: "Successfully updated items"
}
每个语句都使用键值对来获取和操作哈希。
flash.each do |key, value|
#doSomething
end
在这种情况下,键是 "notice",值是 "Successfully updated items"。
在这种情况下,flash
是一个散列 http://docs.ruby-lang.org/en/2.0.0/Hash.html,这意味着有 keys
和 values
像字典一样存储。它与您可能习惯使用的常规变量有点不同。为了帮助您理解这个概念,您可以将散列内部的键视为子变量。当您使用 .each
之类的东西遍历哈希时,您将始终首先获得键,然后是值,键永远不会是 nil
但值可能是
例子
def update
if @item.update(item_params)
# This line is saying redirect and add a key, value to the
# flash hash, with the key being 'notice' and the 'value'
# "Successfully updated items"
redirect_to @item, notice: "Successfully updated items"
else
render 'edit'
end
end
你在上面问了一个问题,如果你只有一个变量,它是键还是值。它也不会是它只是一个变量。
例子
str = 'Hello'
content_tag :div, str, class: "alert alert-info"
#output => "Hello"