From: 7stud -- Date: 2009-05-11T08:55:38+09:00 Subject: Re: Adding data to text file variables 7stud -- wrote: > > template = ERB.new(file_contents) > name, clothing, adj = "Diane", "dress", "lovely" > > new_contents = template.result > puts new_contents > > --output:-- > > The result method looks for the variables name, clothing, and adj in the > current scope. Uhmm...not quite. The result method actually looks for the name, clothing, and adj variables in the "toplevel" scope, i.e. the global scope. Look at this example: require 'erb' def replace(str) name, clothing, adj = "Joe", "hat", "chilly" template = ERB.new(str) new_contents = template.result end name, clothing, adj = "Diane", "dress", "lovely" file_contents =<. I see that you are wearing a new <%= clothing %>. That looks good on you. What a <%= adj %> day it is today. Goodbye. ENDOFSTRING puts replace(file_contents) --output:-- Hello there Diane. I see that you are wearing a new dress. That looks good on you. What a lovely day it is today. Goodbye. The result method did not see the the local variables name, clothing, adj because by default it is programmed to look in the toplevel scope. However, result takes an argument that specifies what scope result should look in for the values of the variables specified in the template. And the Kernel method "binding" can be called to return the surrounding scope. As a result, you can do this: require 'erb' def replace(str) name, clothing, adj = "Joe", "hat", "chilly" template = ERB.new(str) new_contents = template.result(binding) end name, clothing, adj = "Diane", "dress", "lovely" file_contents =<. I see that you are wearing a new <%= clothing %>. That looks good on you. What a <%= adj %> day it is today. Goodbye. ENDOFSTRING puts replace(file_contents) --output:-- Hello there Joe. I see that you are wearing a new hat. That looks good on you. What a chilly day it is today. Goodbye. -- Posted via http://www.ruby-forum.com/.