在哈希中转义ruby值

时间:2015-01-09 18:07:11

标签: ruby hashmap escaping

我在声明ruby哈希时尝试使用其他变量的值。这些价值现在正如我预期的那样被逃脱。我该如何解决这个问题?

变量

ipa_url,名称,版本和包标识符

data = {
            plist: {
              dict: {
                key: 'items',
                array: {
                  dict: {
                    key: %w('assets','metadata'),
                    array: {
                      dict: [{ key:    %w('kind','url'),
                               string: %w('software-package',
                                          "#{ipa_url") },
                             { key:    %w('kind','url'),
                               string: %w('display-image',"#{icon_url.to_s}") },
                             { key:    %w('kind','url'),
                               string: %w('full-size-image',
                                          "#{icon_url}") }],
                      dict: { key: %w('bundle-identifier','bundle-version',
                                      'kind','title'),
                              string: %w("#{bundle-identifier}","#{version}",
                                         'software',"#{name}")
                      }
                    }
                  }
                }
              }
            }
          }

2 个答案:

答案 0 :(得分:3)

%w标识符用于从空格分隔的文本中创建数组:

%w(this is a test)
# => ["this", "is", "a", "test"]

如果你想在那里使用字符串插值,你应该使用%W代替:

variable = 'test'
%W(this is a #{variable})
# => ["this", "is", "a", "test"]

答案 1 :(得分:1)

zenspider详细讨论了这一点,但出于其他目的,这里是细分:

%q(无内插)

[6] pry(main)> hey
=> "hello"
[7] pry(main)> hash = { 'hi' => %q("#{hey}", 'how are you') }
=> {"hi"=>"\"\#{hey}\", 'how are you'"}

%Q(插值和反斜杠)

[8] pry(main)> hash = { 'hi' => %Q("#{hey}", 'how are you') }
=> {"hi"=>"\"hello\", 'how are you'"}

%(插值和反斜杠)

[9] pry(main)> hash = { 'hi' => %("#{hey}", 'how are you') }
=> {"hi"=>"\"hello\", 'how are you'"}
Uri显示

%W(插值)

[7] pry(main)> hash = { 'hi' => %W(#{hey} how are you) }
=> {"hi"=>["hello", "how", "are", "you"]}