user = User.new
user.name ||= '默认值'
| 使用&
area = Area.new
user.area = area
user.area&.area_name
| 使用delegate
delegate :area_name, to: :area, allow_nil: true
| user.balance = 23.027
user.balance.to_i.zero? ? format(‘%.2f’, user.balance) # to_i 可以防止空指针
使用rescue => ex
代替rescue StandardError => ex
rescue => ex # 默认捕获StandardError, 推荐一般捕捉StandardError
test = ''
if user.balance.to_i.zero?
test = 'if值'
else
test = 'else值'
end
||
test = if user.balance.to_i.zero?
'if值'
else
'else值'
end
ActiveRecord::Base.transaction do
=> transaction do
user1 = User.new
user2 = User.new
| 目标:获取用户 user 的 id 数组 我之前的写法是这样的
user_id_array = []
[user1, user2].each do |user|
user_id_array << user1.id
end
||
user_id_array = [user1, user2].map(&:id) # map() 提取数组某元素,组合成新的数组
| 变量和字符串的拼接 | user.name = '中国'
> ’我爱你‘ + user.name
> “我爱你中国”
||
> "我爱你#{user.name}"
> “我爱你中国”