-4

This code is in my book, there are 2 lines that I don't understand.

# library.rb

class Library
   def initialize
       @books ={}  #creating a new hash
   end
   def addBook(book) 
       @books[book.category]||=[]          #category is a symbol. I DONT UNDERSTAND THIS LINE
       @books[book.category] << book       #AND THIS ONE
    end
end
Holger Just
  • 52,918
  • 14
  • 115
  • 123
TheKilz
  • 321
  • 1
  • 3
  • 10

2 Answers2

2
@books ={}

Above line will create a new Hash

@books[book.category]||=[] 

This means @books is a Hash and book.category is it's key and if that key not exist assign an empty array

||= -> So this means or-equals

|| means if @books has value it will not assign empty array, else it will put an empty array

So if @books[book.category] is a Array, in which you can insert as many category values

In this line we will insert book value into the hash, where book.category is the key

   @books[book.category] << book    

If you try this

@books ={}
@books[book.category].push(book) # This will give you the error `undefined method 'push' for nilclass`

because

@books[book.category].class will return NilClass
Sonalkumar sute
  • 2,565
  • 2
  • 17
  • 27
0

a ||= b means "if a is logically false (nil, false, undefined), assign b to it". You can read more about ||=, called "double pipe or equals" here.

So, in your code, @books[book.category] ||= [] means that an empty array ([]) will be assigned to books[book.category] if it's nil - otherwise it will remain intact.

Then, in the line below (@books[book.category] << book), book is appended (<<) to the array. Notice, however, that you have a syntax error (you open a { and you close with a [).

sebkkom
  • 1,426
  • 17
  • 31