#{在Ruby中做什么?
可能重复:#{在Ruby中做什么?,ruby,Ruby,可能重复: 我知道它是用于元编程的,我很难想象这个操作符在下面的例子中做了什么: class Class def attr_accessor_with_history(attr_name) attr_name = attr_name.to_s # make sure it's a string attr_reader attr_name attr_reader attr_name+"_history" class_eval %Q" def #{
我知道它是用于元编程的,我很难想象这个操作符在下面的例子中做了什么:
class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s # make sure it's a string
attr_reader attr_name
attr_reader attr_name+"_history"
class_eval %Q"
def #{attr_name}=(value)
if !defined? @#{attr_name}_history
@#{attr_name}_history = [@#{attr_name}]
end
@#{attr_name} = value
@#{attr_name}_history << value
end
"
end
end
class Foo
attr_accessor_with_history :bar
end
类
def attr_访问器_和_历史记录(attr_名称)
attr_name=attr_name.to_s#确保它是一个字符串
属性读取器属性名称
属性读取器属性名称+“\u历史”
等级_评估%Q“
def#{attr_name}=(值)
如果!已定义?@#{attr_name}\u历史
@#{attr_name}{attr_name}历史=[@#{attr_name}]
结束
@#{attr_name}=value
@#{attr_name}{u history{var}
在Ruby中进行变量替换。例如:
var=“你好,我的名字是#{name}”
您发布的代码正在为您传入的attr_名称生成一个带有访问器方法代码的字符串。{var}
在Ruby中进行变量替换。例如:
var=“你好,我的名字是#{name}”
您发布的代码正在为您传入的attr_名称生成一个带有访问器方法代码的字符串。实际上没有什么作用:D.所有的红色文本基本上只是一个字符串。“bla{var}bla”部分只是编写“bla”+var+“bla”的一种更好的方式。在irb中自己尝试一下:
a = 10
puts "The Joker stole #{a} pies."
它实际上没什么作用:D.所有的红色文本基本上只是一个字符串。“bla{var}bla”部分只是写“bla”+var+“bla”的一种更好的方式。在irb中自己尝试一下:
a = 10
puts "The Joker stole #{a} pies."
一般来说,{…}
计算其中的任何内容,并将其返回,转换为字符串,使用to_s
。这使得在单个字符串中组合多个内容变得更加容易
一个典型的例子是:
"There are #{n} car#{n == 1 ? '' : 's'} in the #{s}"
这相当于:
"There are " + n.to_s + " car" + (n == 1 ? '' : 's').to_s + " in the " + s.to+_s
重要的是要记住,#{…}
插值的内容实际上是一块Ruby代码,其结果将在组合之前转换为字符串
这个元编程的例子非常懒惰,因为instance\u variable\u get
和instance\u variable\u set
本可以被使用,而且eval
本可以避免。大多数时候,你会看到字符串插值被用来创建字符串,而不是方法或类
使用String#%
方法有一个更健壮的格式化程序:
"There are %d car%s in the %s" % [ n, (n == 1 ? '' : 's'), s ]
这可以用于添加精确的小数位数、用空格填充字符串以及其他有用的内容。一般来说,{…}
计算其中的任何内容,并将其转换为字符串,并将其转换为to_s
。这使得在单个字符串中组合多个内容变得更加容易
一个典型的例子是:
"There are #{n} car#{n == 1 ? '' : 's'} in the #{s}"
这相当于:
"There are " + n.to_s + " car" + (n == 1 ? '' : 's').to_s + " in the " + s.to+_s
重要的是要记住,#{…}
插值的内容实际上是一块Ruby代码,其结果将在组合之前转换为字符串
这个元编程的例子非常懒惰,因为instance\u variable\u get
和instance\u variable\u set
本可以被使用,而且eval
本可以避免。大多数时候,你会看到字符串插值被用来创建字符串,而不是方法或类
使用String#%
方法有一个更健壮的格式化程序:
"There are %d car%s in the %s" % [ n, (n == 1 ? '' : 's'), s ]
这可用于添加精确的小数位数、用空格填充字符串以及其他有用的内容。它所做的工作称为变量插值
name = "Bond"
p "The name is #{name}. James #{name}."
将输出
> "The name is Bond. James Bond."
它的作用称为变量插值
name = "Bond"
p "The name is #{name}. James #{name}."
将输出
> "The name is Bond. James Bond."
它被称为变量插值而不是替换。它应该是{name}
而不是{{name}
。它被称为变量插值而不是替换。它应该是{name}
而不是{name}
。