我正在尝试从文件中读取一个字符串,该字符串插入代码中定义的变量,并替换这些变量的字符串值。
文本文件:
my name is #{name}
代码:
file = File.open("tesst.txt", "r")
arr = []
name = "CDJ"
file.each_line.with_index { |line, index|
puts line
}
file.close
期望的输出:
My name is CDJ
实际输出:
My name is #{name}
当输出为line.inspect时:
"My name is \#{name}"
任何人都可以帮我正确格式化这个字符串,所以它将#{name}作为变量而不是带有插入的转义字符的字符串读取吗?
答案 0 :(得分:1)
file= 'tesst.txt'
name = 'CDJ'
File.readlines(file).each do |line|
eval("puts \"#{line}\"")
end
答案 1 :(得分:0)
考虑一下:
jQuery(function($) {
var $container = $('#isotope-list'); //The ID for the list with all the blog posts
$container.isotope({ //Isotope options, 'item' matches the class in the PHP
itemSelector: '.item',
layoutMode: 'masonry'
});
// Add class when transition is finished
$container.on( 'arrangeComplete', function( event, filteredItems ) {
$(".grid figure img").addClass("imgArranged");
});
//Add the class selected to the item that is clicked, and remove from the others
var $optionSets = $('#filters,#filters-undercat'),
$optionLinks = $optionSets.find('a');
$optionLinks.click(function() {
var $this = $(this);
// don't proceed if already selected
if ($this.hasClass('selected')) {
return false;
}
var $optionSet = $this.parents('#filters');
$optionSets.find('.selected').removeClass('selected');
$this.addClass('selected');
//When an item is clicked, sort the items.
var selector = $(this).attr('data-filter');
$container.isotope({
filter: selector
});
return false;
});
});
备注强>:
class Template
def initialize(source: DATA)
@text = source.read.chomp.split("\n")
end
def render(locals: {})
locals.each do |key, value|
instance_variable_set("@#{key}", value)
self.class.send(:attr_reader, key)
end
@text
.map { |line| eval("\"#{line}\"") }
.join("\n")
end
end
puts Template
.new(source: File.open('./tesst.txt', 'r'))
.render(locals: {name: 'George', age: 29})
__END__
my name is #{name}
I am #{age} years old
切换File
,以便在DATA