【问题标题】:Ruby: Merging variables in to a stringRuby:将变量合并到字符串中
【发布时间】:2010-10-07 23:13:24
【问题描述】:

我正在寻找一种在 Ruby 中将变量合并为字符串的更好方法。

例如,如果字符串是这样的:

animalactionsecond_animal

我有 animalactionsecond_animal 的变量,将这些变量放入字符串的首选方法是什么?

【问题讨论】:

    标签: ruby string


    【解决方案1】:

    惯用的方式是这样写:

    "The #{animal} #{action} the #{second_animal}"
    

    注意字符串周围的双引号 ("):这是 Ruby 使用其内置占位符替换的触发器。您不能用单引号 (') 替换它们,否则字符串将保持原样。

    【讨论】:

    • 对不起,也许我把问题简化得太多了。字符串将从数据库中提取,并且变量取决于许多因素。通常我会使用一个替换 1 或两个变量,但这有可能更多。有什么想法吗?
    • #{} 构造可能是最快的(尽管这对我来说仍然违反直觉)。和gix的建议一样,你也可以用+或者
    • 内插变量的最佳方法
    【解决方案2】:

    您可以使用类似 sprintf 的格式将值注入字符串。为此,字符串必须包含占位符。将您的参数放入数组并使用以下方式: (更多信息请查看the documentation for Kernel::sprintf。)

    fmt = 'The %s %s the %s'
    res = fmt % [animal, action, other_animal]  # using %-operator
    res = sprintf(fmt, animal, action, other_animal)  # call Kernel.sprintf
    

    您甚至可以明确指定参数编号并将它们随机排列:

    'The %3$s %2$s the %1$s' % ['cat', 'eats', 'mouse']
    

    或者使用哈希键指定参数:

    'The %{animal} %{action} the %{second_animal}' %
      { :animal => 'cat', :action=> 'eats', :second_animal => 'mouse'}
    

    请注意,您必须为% 运算符的所有参数提供一个值。例如,你不能避免定义animal

    【讨论】:

      【解决方案3】:
      ["The", animal, action, "the", second_animal].join(" ")
      

      是另一种方法。

      【讨论】:

        【解决方案4】:

        标准 ERB 模板系统可能适用于您的方案。

        def merge_into_string(animal, second_animal, action)
          template = 'The <%=animal%> <%=action%> the <%=second_animal%>'
          ERB.new(template).result(binding)
        end
        
        merge_into_string('tiger', 'deer', 'eats')
        => "The tiger eats the deer"
        
        merge_into_string('bird', 'worm', 'finds')
        => "The bird finds the worm"
        

        【讨论】:

          【解决方案5】:

          如其他答案所述,我将使用 #{} 构造函数。 我还想指出,这里有一个真正的微妙之处需要注意:

          2.0.0p247 :001 > first_name = 'jim'
           => "jim" 
          2.0.0p247 :002 > second_name = 'bob'
           => "bob" 
          2.0.0p247 :003 > full_name = '#{first_name} #{second_name}'
           => "\#{first_name} \#{second_name}" # not what we expected, expected "jim bob"
          2.0.0p247 :004 > full_name = "#{first_name} #{second_name}"
           => "jim bob" #correct, what we expected
          

          虽然可以使用单引号创建字符串(如 first_namelast_name 变量所示,#{} 构造函数只能用于带双引号的字符串。

          【讨论】:

            【解决方案6】:

            这称为字符串插值,你可以这样做:

            "The #{animal} #{action} the #{second_animal}"
            

            重要提示:仅当字符串在双引号(“”)内时才有效。

            无法按预期工作的代码示例:

            'The #{animal} #{action} the #{second_animal}'
            

            【讨论】:

            • 感谢您使用正确的术语,以便新程序员可以学习:插值。
            【解决方案7】:

            您可以将它与本地变量一起使用,如下所示:

            @animal = "Dog"
            @action = "licks"
            @second_animal = "Bird"

            "The #{@animal} #{@action} the #{@second_animal}"

            输出将是:“

            【讨论】:

              猜你喜欢
              • 2013-04-12
              • 1970-01-01
              • 2017-10-22
              • 1970-01-01
              • 2021-02-03
              • 2013-03-25
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多