0
0
Rubyprogramming~10 mins

Open struct for dynamic objects in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a new OpenStruct object.

Ruby
require 'ostruct'
obj = [1].new
Drag options to blanks, or click blank then click option'
AObject
BStruct
CHash
DOpenStruct
Attempts:
3 left
💡 Hint
Common Mistakes
Using Struct instead of OpenStruct
Using Object which is too general
2fill in blank
medium

Complete the code to set a dynamic attribute 'name' to 'Alice'.

Ruby
require 'ostruct'
obj = OpenStruct.new
obj.[1] = 'Alice'
Drag options to blanks, or click blank then click option'
Aname
Bkey
Cattr
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'value' or 'attr' instead of 'name'
3fill in blank
hard

Complete the code to access a missing attribute that returns nil instead of raising an error.

Ruby
require 'ostruct'
obj = OpenStruct.new
puts obj.[1]
Drag options to blanks, or click blank then click option'
Aname
Bundefined
Cnonexistent
Dmissing_attr
Attempts:
3 left
💡 Hint
Common Mistakes
Expecting an error when accessing missing attributes
4fill in blank
hard

Fill both blanks to create an OpenStruct with the 'age' attribute set to 30.

Ruby
require 'ostruct'
obj = OpenStruct.new([1] => [2])
Drag options to blanks, or click blank then click option'
A:age
B30
C'city' => 'Paris'
D:city
Attempts:
3 left
💡 Hint
Common Mistakes
Using string keys instead of symbols
Incorrect hash syntax
5fill in blank
hard

Fill all three blanks to add a new attribute 'country' with value 'France' to an existing OpenStruct object.

Ruby
require 'ostruct'
obj = OpenStruct.new(city: 'Paris')
obj.[1] = [2]
puts obj.[3]
Drag options to blanks, or click blank then click option'
Acountry
B'France'
Dcity
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong attribute names
Forgetting quotes around string values