Common Ruby Idioms

前端 未结 15 1971
星月不相逢
星月不相逢 2020-12-07 07:13

One thing I love about ruby is that mostly it is a very readable language (which is great for self-documenting code)

However, inspired by this question: Ruby Code ex

15条回答
  •  抹茶落季
    2020-12-07 07:20

    I always forget the exact syntax of this shorthand if else statement (and the name of the operator. comments anyone?) I think it's widely used outside of ruby, but in case someone else wants the syntax here it is:

    refactor < 3 ? puts("No need to refactor YET") : puts("You need to refactor this into a  method")
    

    expands to

    if refactor < 3
      puts("No need to refactor YET")
    else
      puts("You need to refactor this into a  method")
    end
    

    update

    called the ternary operator:

    return myvar ? myvar.size : 0

提交回复
热议问题