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

前端 未结 8 1832
抹茶落季
抹茶落季 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 11:09

    Well, I second stesch's answer of using erb in this situation. But you can use eval like this. If data.txt has contents:

    he #{foo} he
    

    Then you can load and interpolate like this:

    str = File.read("data.txt")
    foo = 3
    result = eval("\"" + str + "\"")
    

    And result will be:

    "he 3 he"
    

提交回复
热议问题