Antarr Byrd
Antarr Byrd

Reputation: 26071

escaping ruby values in hash

I'm trying to use the values of other variable when declaring a ruby hash. Those values are now being escaped as I expected. How can I fix this?

variables

ipa_url, name, version and bundle-identifier

code

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}")
                      }
                    }
                  }
                }
              }
            }
          }

Upvotes: 0

Views: 149

Answers (2)

Anthony
Anthony

Reputation: 15967

zenspider goes over this in detail but for SO purposes, here's the breakdown:

%q(no interpolation)

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

%Q(interpolation and backslashes)

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

%(interpolation and backslashes)

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

%W(interpolation) as Uri showed:

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

Upvotes: 1

Uri Agassi
Uri Agassi

Reputation: 37409

The %w identifier is used to created an array out of a space delimited text:

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

If you want to use string interpolation there, you should use %W instead:

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

Upvotes: 3

Related Questions