带嵌入变量的Ruby字符串

时间:2012-05-31 14:01:44

标签: ruby

如何在yaml中存储带有嵌入变量的ruby字符串,但只有当我从yaml获取字符串时才插入变量值?

2 个答案:

答案 0 :(得分:20)

str = "Hi %{name}, %{msg}. Bye %{name}." #yaml it, de-yaml it back to string
h = {:name=> "John", :msg=> "this message is for you"}
puts str % h
#=>Hi John, This message is for you. Bye John.

答案 1 :(得分:2)

将rails在eram文件中嵌入到rails中:

# config/initializers/load_config.rb
APP_CONFIG = YAML.load_file("#{Rails.root}/config/app_config.yml")[Rails.env]


# config/app_config.yml
development:
  key1: <%= # ruby code ... %>
test:
  key1: <%= # ruby code ... %>
production:
  key1: <%= # ruby code ... %>