ruby 声明case、if语句的更易读的形式是什么[已关闭]

vlurs2pr  于 2023-06-05  发布在  Ruby
关注(0)|答案(3)|浏览(105)

已关闭,此问题为opinion-based。目前不接受答复。
**想改善这个问题吗?**更新问题,以便editing this post可以用事实和引用来回答。

5天前关闭。
Improve this question
我收到了关于一个ruby公关的有趣评论,我想听听更广泛的意见。我在这个表格中提交了一个代码。

def check_form1(l)
  if !l.a
    if !l.b
      action1(l)
      if l.c
        return "abc"
      else
        return "ab"
      end
    elsif l.c
      return "c"
    end
  end
end

并收到了一条评论,说这会更具可读性。

def check_form2(l)
  d = !l.a && !l.b
  if d
    action1(l)
  end
  return "abc" if d && l.c
  return "ab" if d && !l.c
  return "c" if !l.a && l.c
end

我更喜欢第一种形式,因为它更好地可视化了所有其他情况,因此感觉更完整。
你的意见是什么?

zpf6vheq

zpf6vheq1#

例1

def check_form1(l)
  return unless l.a

  unless l.b
    action1(l)
    return l.c ? 'abc' : 'ab'
  end
  return 'c' if l.c
end

例2

def check_form1(l)
  return if !l.a
  return 'c' if l.b && l.c
  return if !l.b
  
  action1(l) 
  l.c ? 'abc' : 'ab'
end

Ex3

def check_form1(l)
  return unless l.a
  return 'c' unless !(l.b && l.c)
  return unless l.b

  action1(l) 
  l.c ? 'abc' : 'ab'
end
7qhs6swi

7qhs6swi2#

给予你的变量一个名字,避免写否定条件。
我不能帮助你的变量名,我只能显示我将如何编写函数。如果存在变量名,则可能存在一些更可读的形式。这样我只能尽量避免否定和嵌套,使它更清晰。

def check_form1(l)
  return if l.a # make it clear when the function does nothing on the first line
  return 'c' if l.b && l.c
  return if l.b
  
  action(l)
  return l.c ? "abc" : "ab"
end
rqdpfwrv

rqdpfwrv3#

这当然是自以为是的,但我会这样做:

def check_form1(l)
  return     if l.a
  return 'c' if !l.b && l.c
  return     unless l.b 

  action1(l) 
  l.c ? 'abc' : 'ab'
end

或者

def check_form1(l)
  case
  when !l.a 
    nil
  when !l.b && l.c
    'c'
  when l.b && l.c
    action1(l)
    'abc'
  when l.b && !l.c
    action1(l)
    'ab'
  end
end

相关问题