嵌套动态数组 rails
Nested dynamic array rails
我创建了一个数组
steps = [{'title' =>'abc','content' =>'click this', 'target' => 'bca'}]
tours = ['id'=>'tour', 'steps:' => "#{steps}"]
puts tours
获得以下输出:
{"id"=>"tour", "steps:"=>"[{\"title\"=>\"abc\", \"content\"=>\"click this\", \"target\"=>\"bca\"}]"}
输出的结构是正确的,但我不希望输出中出现这些 \
。
我应该怎么做才能删除这些 \
。
谢谢!
In ruby "#{}"
调用对象的 to_s
方法。你可以检查它运行下面的代码:steps.to_s
.
只需使用:
tours = ['id'=>'tour', 'steps:' => steps]
因为这个:
"[{\"title\"=>\"abc\", \"content\"=>\"click this\", \"target\"=>\"bca\"}]"
是以下的字符串表示形式:
[{'title' =>'abc','content' =>'click this', 'target' => 'bca'}]
Зелёный
为您提供了直接答案,但是,我要指出一个更紧迫的问题——我认为您在 {hashes}
和 [arrays]
[ 之间感到困惑=22=]
--
数组是一组无序数据:
array = [3, 4, 5, 6, 0, 5, 3, "cat", "dog"]
数组主要用于非顺序数据集合,购物车中的 product_ids
就是一个很好的例子。
数组只能通过数据在数组中的位置来识别:
array[1] # -> 4
array[2] # -> 5
--
哈希是 key:value
对的集合:
hash = {name: "Greg", type: "cat"}
当你想给一个数据分配多个值时使用散列,可以通过引用散列的"key"来调用:
hash["name"] #-> Greg
hash["type"] #-> cat
虽然您可以创建一个哈希数组:
hash_array = [{name: "Greg", type: "cat"}, {name: "Sulla", type: "Dog"}]
...问题在于您不能直接调用散列 - 它们必须 through 数组:
hash_array["name"] # -> error
hash_array[0]["name"] #-> "Greg"
因此,我将在您的示例中使用以下内容:
steps = {'title' =>'abc','content' =>'click this', 'target' => 'bca'}
tours = {id: 'tour', steps: steps}
tours.inspect #-> { id: "tour", steps: { "title" => "abc", "content" => "click this", "target" => "bca" }
我创建了一个数组
steps = [{'title' =>'abc','content' =>'click this', 'target' => 'bca'}]
tours = ['id'=>'tour', 'steps:' => "#{steps}"]
puts tours
获得以下输出:
{"id"=>"tour", "steps:"=>"[{\"title\"=>\"abc\", \"content\"=>\"click this\", \"target\"=>\"bca\"}]"}
输出的结构是正确的,但我不希望输出中出现这些 \
。
我应该怎么做才能删除这些 \
。
谢谢!
In ruby "#{}"
调用对象的 to_s
方法。你可以检查它运行下面的代码:steps.to_s
.
只需使用:
tours = ['id'=>'tour', 'steps:' => steps]
因为这个:
"[{\"title\"=>\"abc\", \"content\"=>\"click this\", \"target\"=>\"bca\"}]"
是以下的字符串表示形式:
[{'title' =>'abc','content' =>'click this', 'target' => 'bca'}]
Зелёный
为您提供了直接答案,但是,我要指出一个更紧迫的问题——我认为您在 {hashes}
和 [arrays]
[ 之间感到困惑=22=]
--
数组是一组无序数据:
array = [3, 4, 5, 6, 0, 5, 3, "cat", "dog"]
数组主要用于非顺序数据集合,购物车中的 product_ids
就是一个很好的例子。
数组只能通过数据在数组中的位置来识别:
array[1] # -> 4
array[2] # -> 5
--
哈希是 key:value
对的集合:
hash = {name: "Greg", type: "cat"}
当你想给一个数据分配多个值时使用散列,可以通过引用散列的"key"来调用:
hash["name"] #-> Greg
hash["type"] #-> cat
虽然您可以创建一个哈希数组:
hash_array = [{name: "Greg", type: "cat"}, {name: "Sulla", type: "Dog"}]
...问题在于您不能直接调用散列 - 它们必须 through 数组:
hash_array["name"] # -> error
hash_array[0]["name"] #-> "Greg"
因此,我将在您的示例中使用以下内容:
steps = {'title' =>'abc','content' =>'click this', 'target' => 'bca'}
tours = {id: 'tour', steps: steps}
tours.inspect #-> { id: "tour", steps: { "title" => "abc", "content" => "click this", "target" => "bca" }