In Ruby, can you perform string interpolation on data read from a file?

前端 未结 8 1828
抹茶落季
抹茶落季 2020-12-10 10:37

In Ruby you can reference variables inside strings and they are interpolated at runtime.

For example if you declare a variable foo equals \"Ted\

8条回答
  •  天命终不由人
    2020-12-10 10:55

    I think this might be the easiest and safest way to do what you want in Ruby 1.9.x (sprintf doesn't support reference by name in 1.8.x): use Kernel.sprintf feature of "reference by name". Example:

    >> mystring = "There are %{thing1}s and %{thing2}s here."
     => "There are %{thing1}s and %{thing2}s here."
    
    >> vars = {:thing1 => "trees", :thing2 => "houses"}
     => {:thing1=>"trees", :thing2=>"houses"}
    
    >> mystring % vars
     => "There are trees and houses here." 
    

提交回复
热议问题