Ruby: Control Structure

Conditions

  • if-elsif-else(basic):
    • basic condition control structure, will do anything you want.
    • trick1: when you assign a value to a variable behind if
      • that variable can only be used in the multiline scheme.
      • that variable cannot be used in the single line scheme.
    • trick2: when you define a variable inside the conditional block.
      • you can use it outside the conditional block
      • when the condition is false, outside variable value is nil.
      • both single line and multiline schemes can use this feature.
  • case-when-else(switch):
    • has clear structure than the basic if-else structure.
    • internally use the ruby triple equal operator === to compare.
    • a === b means "if 'a' describe a set, would 'b' be a member of that set?"
      • when range and element: (1..5) === 3
      • when class and class: Object === String
      • when class and object: Object === 'string'
      • when regex and string: /foo/ === 'foobar'
      • you can also rewrite object === method
  • ternary-operator(terse):
    • only use one line code, look so pretty :P_
    • suit with simple statement, shouldn't be too complex.
    • also use for assignment with condition: a = condition ? b : c
  • && (and) vs || (or):
    • a && b can convert to: b if a
    • a || b can convert to: b if not a
    • assign with default value: x = a || b
    • assign if not assigned before: x ||= c

Loops

  • iterators:
    • (basic) each, select, map, reduce...
    • (numbers) times, upto, downto, step...
  • traditional-loop:
    • loop: infinite loop, use break to stop it.
      • use case: generate unique random keys.
  • control-keywords:
    • break: says quit immediately.
    • next: says loop immediately.
    • redo: says redoes that same loop over again.
    • retry: says starts the whole loop over from the beginning.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容