#{在Ruby中做什么?

时间:2013-02-03 01:46:01

标签: ruby

  

可能重复:
  Meaning of #{ } in 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 #{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

4 个答案:

答案 0 :(得分:2)

一般而言,#{...}会评估其中的内容并返回该内容,并将其转换为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_variable_getinstance_variable_set可以使用,eval可以避免。大多数情况下,您会看到用于创建字符串的字符串插值,而不是方法或类。

使用String#%方法有一个更强大的格式化程序:

"There are %d car%s in the %s" % [ n, (n == 1 ? '' : 's'), s ]

这可用于添加精确的小数位数,填充带空格的字符串以及其他有用的东西。

答案 1 :(得分:1)

#{var}在Ruby中进行变量替换。例如:

var = "Hello, my name is #{name}"

您发布的代码是生成一个字符串,其中包含您传入的attr_name的访问器方法的代码。

答案 2 :(得分:0)

实际上做得不多:D。所有红色文本基本上只是一个字符串。 “bla#{var} bla”部分只是编写“bla”+ var +“bla”的更好方法。在irb中自己尝试一下:

a = 10
puts "The Joker stole #{a} pies." 

答案 3 :(得分:0)

它的作用叫做variable interpolation

name = "Bond"
p "The name is #{name}. James #{name}."

将输出,

> "The name is Bond. James Bond."
相关问题