# bad
arr = Array.new
hash = Hash.new
# good
arr = []
hash = {}
# bad STATES = ['draft', 'open', 'closed'] # good STATES = %w(draft open closed)
# bad STATES = [:draft, :open, :closed] # good STATES = %i(draft open closed)
# bad - easier to move/add/remove items, but still not preferred
VALUES = [
1001,
2020,
3333,
]
# bad
VALUES = [1001, 2020, 3333, ]
# good
VALUES = [1001, 2020, 3333]
arr = [] arr[100] = 1 # now you have an array with lots of nils
# bad
hash = { 'one' => 1, 'two' => 2, 'three' => 3 }
# good
hash = { one: 1, two: 2, three: 3 }
# bad
hash = { :one => 1, :two => 2, :three => 3 }
# good
hash = { one: 1, two: 2, three: 3 }
# bad
{ a: 1, 'b' => 2 }
# good
{ :a => 1, 'b' => 2 }
# bad hash.has_key?(:test) hash.has_value?(value) # good hash.key?(:test) hash.value?(value)
heroes = { batman: 'Bruce Wayne', superman: 'Clark Kent' }
# bad - if we make a mistake we might not spot it right away
heroes[:batman] # => "Bruce Wayne"
heroes[:supermann] # => nil
# good - fetch raises a KeyError making the problem obvious
heroes.fetch(:supermann)
batman = { name: 'Bruce Wayne', is_evil: false }
# bad - if we just use || operator with falsy value we won't get the expected result
batman[:is_evil] || true # => true
# good - fetch work correctly with falsy values
batman.fetch(:is_evil, true) # => false
batman = { name: 'Bruce Wayne' }
# bad - if we use the default value, we eager evaluate it
# so it can slow the program down if done multiple times
batman.fetch(:powers, get_batman_powers) # get_batman_powers is an expensive call
# good - blocks are lazy evaluated, so only triggered in case of KeyError exception
batman.fetch(:powers) { get_batman_powers }
# bad
email = data['email']
nickname = data['nickname']
# good
email, username = data.values_at('email', 'nickname')
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有