【问题标题】:Call a function within Quotes " "在引号“”中调用函数
【发布时间】:2021-10-29 08:17:00
【问题描述】:

我是 Ruby 的初学者。有人可以帮我解决这个问题吗? 我想在“”中调用一个方法

def callme
"this string"  # this is usually a path that I want to source from a single location 
end               


v= "string + callme "

如何在这里用引号调用函数?引号对我的代码至关重要。

【问题讨论】:

  • 当你说“引号对我的代码很重要”时你能解释一下吗?预期结果是"string + this string""string this string" 还是"string + \"this string\"" 等,目前还不清楚。顺便说一句,作为一个小的语法建议,ruby 中没有 functions,只有 methods

标签: ruby string function


【解决方案1】:

你可以使用字符串插值/连接:

def hi
  'Hello'
end

def world
  'World'
end

# Concatenation
hi + ' ' + world   #=> "Hello World"

# Interpolation
"#{hi} #{world}"   #=> "Hello World"

详情请见this answer

【讨论】:

    【解决方案2】:

    如果我理解正确,您正在寻找的是字符串插值。其语法为#{...},如下所示:

    v= "string + #{callme} "
    

    这会将变量v 设置为"string + this string "

    Reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 2014-02-09
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      • 2018-12-27
      相关资源
      最近更新 更多