Why should you avoid the then keyword in Ruby?

后端 未结 3 350
甜味超标
甜味超标 2021-01-18 00:42

It\'s mentioned in several Ruby style guides that you should \"Never use then.\" Personally, I think the \"then\" keyword allows you to make code denser, which tends to be

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-18 01:22

    I almost never use the then keyword. However, there is one case where I believe it greatly improves readability. Consider the following multi conditional if statements.

    Example A

    if customer.jobs.present? && customer.jobs.last.date.present? && (Date.today - customer.jobs.last.date) <= 90
      puts 'Customer had a job recently'
    end
    

    Line length too long. Hard to read.

    Example B

    if customer.jobs.present? &&
       customer.jobs.last.date.present? &&
       (Date.today - customer.jobs.last.date) <= 90
      puts 'Customer had a job recently'
    end
    

    Where do the conditions end and where does the inner code begin. According to must Ruby Style Guides, you to have one extra space of indentation for multi line conditionals, but I still don't find it all the easy to read.

    Example C

    if customer.jobs.present? &&
       customer.jobs.last.date.present? &&
       (Date.today - customer.jobs.last.date) <= 90
    then
      puts 'Customer had a job recently'
    end
    

    To me, Example C is by far the most clear. And it is the use of the then that does the trick.

提交回复
热议问题