我的应用程序控制器中有一个受保护的方法
def current_user
@current_user ||= User.find_by_id(session[:user_id])
end
Run Code Online (Sandbox Code Playgroud)
我想知道是什么||=意思?我一直试图搜索并找出答案,但无济于事.
有人可以解释这段Ruby代码:
def add_spec_path_to(args) # :nodoc:
args << {} unless Hash === args.last
args.last[:spec_path] ||= caller(0)[2]
end
Run Code Online (Sandbox Code Playgroud)
我已经看到<<运算符用于连接字符串或用作其他语言的按位运算符,但有人可以在此上下文中解释它.它是以某种方式将空白的lamda附加到args上还是我完全错了?
我也可以看到它像这样使用:
before_parts(*args) << block
Run Code Online (Sandbox Code Playgroud)
是Hash关键字吗?
我也不确定||=操作员在说什么.
我在黑暗中同样如此caller(0)[2].
哈希初始值设定项:
# this
animals = Hash.new { [] }
animals[:dogs] << :Scooby
animals[:dogs] << :Scrappy
animals[:dogs] << :DynoMutt
animals[:squirrels] << :Rocket
animals[:squirrels] << :Secret
animals #=> {}
# is not the same as this
animals = Hash.new { |_animals, type| _animals[type] = [] }
animals[:dogs] << :Scooby
animals[:dogs] << :Scrappy
animals[:dogs] << :DynoMutt
animals[:squirrels] << :Rocket
animals[:squirrels] << :Secret
animals #=> {:squirrels=>[:Rocket, :Secret], :dogs=>[:Scooby, :Scrappy, :DynoMutt]}
Run Code Online (Sandbox Code Playgroud)
我看到有人在另一个问题上发布这些内容,但我不明白为什么动物在第一种情况下显得空白.如果我输入
animals[:dogs]
Run Code Online (Sandbox Code Playgroud)
我得到了合适的数组.