0

I have a ruby array like below

tomcats = [
  'sandbox',
  'sandbox_acserver',
  'sandbox_vgw'
]

I need to pass the string as a hash index like below

tomcats.each do |tomcat_name|
  obi_tomcat '#{tomcat_name}' do
    Chef::Log::info("Creating tomcat instance - #{tomcat_name}")
    Chef::Log::info("#{node['obi']['tomcat']['sandbox'][:name]}") // works
    Chef::Log::info("#{node['obi']['tomcat']['#{tomcat_name}'][:name]}") // doesn't work
  end
end

The last log throws an error since the access with #{tomcat_name} is nil. I'm new to ruby. How do I access with key as the tomcat_name ?

3 Answers 3

3

In normal code, you'd write:

node['obi']['tomcat'][tomcat_name][:name]

In a string interpolation (useless here, because it's the only thing in the string in this case), it is completely the same:

"#{node['obi']['tomcat'][tomcat_name][:name]}"
Sign up to request clarification or add additional context in comments.

3 Comments

So basically, calling Chef::Log::info(node['obi']['tomcat'][tomcat_name][:name]) should work!
Yup. You only need interpolation if you want to insert stuff in a bigger string, like in your first info line - "#{foo}" is same as foo, but "Big #{foo}!" is same as "Big " + foo + "!", which is not as readable.
This one may be more useless in this case, but it still work: "#{node['obi']['tomcat']["#{tomcat_name}"][:name]}"
2

#{} only works in double quote, as "#{tomcat_name}".

But you don't need the syntax here, just use [tomcat_name] directly.

Comments

0

When I saw this question, I'm thinking whether ruby placeholder could be put inside other placeholder in string interpolation. And I found that ruby actually support it, and most interesting thing is that you don't need to escape the " inside the string.

Although it is not very useful in this case, it still works if you write as below:

Chef::Log::info("#{node['obi']['tomcat']["#{tomcat_name}"][:name]}")

Below is an simple example of placeholder inside other placeholder:

tomcats = [
  'sandbox',
  'sandbox_acserver',
  'sandbox_vgw'
]

node = {
    'sandbox_name' => "sandbox name",
    'sandbox_acserver_name' => "sandbox_acserver name",
    'sandbox_vgw_name' => "sandbox_vgw name",
}

tomcats.each do | tomcat |
    puts "This is tomcat : #{node["#{tomcat}_name"]}"
end

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.