Ruby Code explained

前端 未结 3 1663
时光取名叫无心
时光取名叫无心 2020-12-10 18:42

Could somebody please explain this piece of Ruby code:

def add_spec_path_to(args) # :nodoc:
  args << {} unless Hash === args.last
  args.last[:spec_pa         


        
3条回答
  •  孤城傲影
    2020-12-10 19:06

    I'm presuming that args is an Array.

    Hash is the name of a class - the first line pushes an empty hash {} onto args unless the last element of args is already a Hash (the === operator for classes tests whether an object is of a certain class).

    The ||= operator is similar to the += operator: it's more or less equivalent to:

    args.last[:spec_path] = args.last[:spec_path] || caller(0)[2]
    

    So, it will set args.last[:spec_path] if and only if it is currently unset.

    The caller method returns info about the calling method.

提交回复
热议问题