【问题标题】:`Case/when` statement works some of the time`Case/when` 语句在某些时候有效
【发布时间】:2014-03-05 14:06:08
【问题描述】:

好的,我正在创建一个 gem,它应该在用户的帖子中找到标签 #@$。我正在使用 case when 语句,它似乎只在某些时候有效。例如,我将有一个类似@you 的字符串,它可以工作,但除非我添加#cool @you,否则#cool 不起作用。似乎其他when 语句仅在第一个when 语句为真时才有效。正则表达式就是这样,它知道要查找什么,而且我知道那些确实有效。

  REGEXS = [Supertag::Tag::USERTAG_REGEX, Supertag::Tag::HASHTAG_REGEX, Supertag::Tag::MONEYTAG_REGEX]

  def linkify_tags(taggable_content)
    text = taggable_content.to_s

    REGEXS.each do
      case text
      when text = text.gsub(Supertag::Tag::USERTAG_REGEX) {link_to($&, usertag_path($2), class: 'tag')}
      when text = text.gsub(Supertag::Tag::HASHTAG_REGEX) {link_to($&, hashtag_path($2), class: 'tag')}
      when text = text.gsub(Supertag::Tag::MONEYTAG_REGEX) {link_to($&, moneytag_path($2), class: 'tag')}
      end  
    end     

    text.html_safe
  end

【问题讨论】:

  • 老实说,不知道为什么这会受到如此多的反对......
  • 我也不明白为什么会这样。这个网站的意义不在于帮助人们吗?

标签: ruby-on-rails ruby


【解决方案1】:

由于某种原因,您迭代了 REGEXS,忽略了迭代中的项目,然后再次对其进行硬编码...实际上您执行了 text.gsub(Supertag::Tag::USERTAG_REGEX) ... 3 次 - 列表中的每个 REGEX 一次。

另外,你误用了case when 结构,我建议你阅读more about it

您应该完全放弃each,只使用显式常量,或者重构您的代码以动态工作,可能类似于:

  REGEXS = [[Supertag::Tag::USERTAG_REGEX, :usertag_path], 
            [Supertag::Tag::HASHTAG_REGEX, :hashtag_path], 
            [Supertag::Tag::MONEYTAG_REGEX, :moneytag_path]]

  def linkify_tags(taggable_content)
    text = taggable_content.to_s

    REGEXS.each do |regex, path|
      text = text.gsub(regex) {link_to($&, send(path, $2), class: 'tag')}
    end     

    text.html_safe
  end

【讨论】:

  • 完美运行。我真的需要重新了解我如何理解这些和if/elsif 声明
猜你喜欢
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-10
  • 2016-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多