【问题标题】:use variable in regexp in ruby [duplicate]在ruby的正则表达式中使用变量[重复]
【发布时间】:2016-12-29 18:52:57
【问题描述】:

有没有办法用变量替换下面代码中的 [aeiou]?询问的原因是我以后是否必须使用辅音来执行此操作,似乎最好定义变量并在正则表达式中使用它,因为我认为它会更干净。

def word_mutation(word)
  vowels = %w[a e i o u]
  if word.match(/^[aeiou]/)
    return word
  else
    return "consonant-starter"
  end
end

所以,我再次尝试使用或只是好奇尝试使用类似的东西:

if word.match(/^vowels/)

谢谢!!

【问题讨论】:

  • irb(main):006:0> word = "vowels" ; myvar = "元音" ; word.match(/^#{myvar}/

标签: ruby regex variables


【解决方案1】:

你可以使用插值,就好像它是一个双引号字符串:

if word.match(/^#{vowels}/)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-19
    • 2011-01-17
    • 2015-01-21
    • 2013-06-17
    • 2017-11-04
    • 2014-01-06
    相关资源
    最近更新 更多