Complete the code to create a symbol named :apple.
fruit = [1]The colon : before a word creates a symbol in Ruby. So :apple is a symbol.
Complete the code to check if two symbols are the same object.
puts :cat.[1] :cat== checks value equality but not object identity.!= is for inequality.The equal? method checks if two objects are the exact same object in memory. Symbols with the same name are the same object.
Fix the error in the code to convert a string to a symbol.
sym = "dog".[1]
to_s returns a string, not a symbol.to_sym! method.The method to_sym converts a string to a symbol in Ruby.
Fill both blanks to create a hash with symbol keys and access a value.
person = { [1] => "Alice", [2] => 30 }
age = person[:age]Symbols are used as keys in hashes for efficiency. Here, :name and :age are symbol keys.
Fill all three blanks to demonstrate symbol immutability and comparison.
sym1 = :car sym2 = :car puts sym1 [1] sym2 puts sym1.object_id [2] sym2.object_id # Trying to change symbol (will cause error) sym3 = :bike # sym3 [3] "cycle" # Uncommenting causes error
replace which do not exist.Symbols with the same name are equal and share the same object id. Symbols cannot be changed once created, so assignment is the only way to set a symbol variable.