0
0
Rubyprogramming~10 mins

To_s method for string representation 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 define a method that returns a string representation of the object.

Ruby
def to_s
  return [1]
end
Drag options to blanks, or click blank then click option'
A"Hello"
Bputs "Hello"
Cprint "Hello"
Dp "Hello"
Attempts:
3 left
💡 Hint
Common Mistakes
Using puts or print instead of returning a string.
2fill in blank
medium

Complete the code to return the string representation of the instance variable @name.

Ruby
def to_s
  @name[1]
end
Drag options to blanks, or click blank then click option'
A.to_i
B.to_f
C.to_a
D.to_s
Attempts:
3 left
💡 Hint
Common Mistakes
Using .to_i or other conversions that do not return strings.
3fill in blank
hard

Fix the error in the to_s method to correctly return a string representation.

Ruby
def to_s
  "Name: " + [1]
end
Drag options to blanks, or click blank then click option'
Ato_s
B@name.to_s
C@name
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using @name without conversion causes error if it's not a string.
4fill in blank
hard

Fill both blanks to create a to_s method that returns a formatted string with name and age.

Ruby
def to_s
  "Name: [1], Age: [2]"
end
Drag options to blanks, or click blank then click option'
A#@name
B@name
C#@age
D@age
Attempts:
3 left
💡 Hint
Common Mistakes
Using instance variables without interpolation syntax inside strings.
5fill in blank
hard

Fill all three blanks to create a to_s method that returns a detailed string with name, age, and city.

Ruby
def to_s
  "Name: [1], Age: [2], City: [3]"
end
Drag options to blanks, or click blank then click option'
A#@name
B#@age
C#@city
D@city
Attempts:
3 left
💡 Hint
Common Mistakes
Using instance variables without interpolation or mixing interpolation and direct variables.