【问题标题】:Rubocop:method has too many linesRubocop:方法的行太多
【发布时间】:2016-02-16 14:51:42
【问题描述】:

您好,我是 ruby​​ 编程的新手。 在我的项目中运行 rubocop 检查,它说:

方法行数过多。 [13/10] 定义刷新状态

这是我的方法:

def refresh_status
    lost = false
    in_progress = false
    won = false
    @bets.each do |bet|
      lost = true if bet.result == :lost
      if bet.result == :canceled
        @to_return /= bet.odd
        won = true
      end
      in_progress = true if bet.result == :in_progress
      won = true if bet.result == :won
    end
    def_result_after_refresh(lost, in_progress, won)
  end

  def def_result_after_refresh(lost, in_progress, won)
    if lost
      @result = :lost
    elsif in_progress
      @result = :in_progress
    elsif won
      @result = :won
    end
  end

找不到缩短该方法的方法,也许您可​​以帮忙?

【问题讨论】:

  • 所有比较bet.result的条件。您可以使用case 语句使您的代码更具表现力,但可能不会更短。因此,您可以在一行中进行初始化,例如lost, in_progress, won = false, false, false
  • rubocop 不允许使用并行(单行)assingments @sschmeck

标签: ruby enumerable rubocop


【解决方案1】:

您可以使用一些Enumerable 方法。

def refresh_status
  @to_return /= @bets.select { |bet| bet.result == :canceled }.map(&:odd).reduce(1, :*)

  results = @bets.map { |bet| bet.result == :cancelled ? :won : bet.result }.uniq
  @result = case
            when results.include?(:lost) then :lost
            when results.include?(:in_progress ) then :in_progress 
            when results.include?(:won) then :won
            end
end

【讨论】:

  • 所以我说我是新手,所以你能说出 map(&:odd) 是做什么的吗?我知道它会将选定的元素列在列表中,但 &:odd 是什么? @sschmeck
  • 好问题。 bets.map(&:odd) 从 bet 数组中构建一个新数组,其中所有赌注都被它的 bet.odd 值替换(或映射)。这是bets.map { |bet| bet.odd } 的快捷方式。它有帮助吗? reduce 很相似。
  • 是的。为了完全接受 rubocop,我需要缩短行数,when results.include?(:won ) then :lost 不太正确,应该是 when results.include?(:won ) then :won 顺便说一句我会接受你的回答
猜你喜欢
  • 2021-03-10
  • 2016-09-10
  • 1970-01-01
  • 1970-01-01
  • 2016-02-03
  • 2022-06-20
  • 2015-09-21
  • 1970-01-01
  • 2013-12-07
相关资源
最近更新 更多