在Ruby中惯用的括号

前端之家收集整理的这篇文章主要介绍了在Ruby中惯用的括号前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. array.include? 'foo' or array.include? 'bar'

是一个语法错误(意外的keyword_or).括号解决问题,但由于我是Ruby的新手,我不知道以下哪一个被认为是更习惯的:

选项1

  1. array.include?('foo') or array.include?('bar')

选项2

  1. (array.include? 'foo') or (array.include? 'bar')

这是否属于个人偏好,还是被认为更为“正确”的方法

解决方法

我建议你看看 community-driven Ruby coding style guide,这里特别是 Syntax的部分.

忽略作为内部DSL(例如Rake,Rails,RSpec)一部分的方法的参数的括号,在Ruby中具有“关键字”状态的方法(例如attr_reader,puts)和属性访问方法.在所有其他方法调用的参数周围使用括号. – 摘自指南

  1. class Person
  2. attr_reader :name,:age
  3.  
  4. # omitted
  5. end
  6.  
  7. temperance = Person.new('Temperance',30)
  8. temperance.name
  9.  
  10. puts temperance.age
  11.  
  12. x = Math.sin(y)
  13. array.delete(e)

猜你在找的Ruby相关文章