0
0
Rubyprogramming~10 mins

Instance variables (@) 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 an instance variable in the initialize method.

Ruby
class Person
  def initialize(name)
    [1] = name
  end
end
Drag options to blanks, or click blank then click option'
A@name
Bname
C$name
Dself.name
Attempts:
3 left
💡 Hint
Common Mistakes
Using a local variable instead of an instance variable.
Using global variable syntax ($) instead of instance variable (@).
2fill in blank
medium

Complete the code to access the instance variable inside a method.

Ruby
class Car
  def initialize(model)
    @model = model
  end

  def show_model
    puts [1]
  end
end
Drag options to blanks, or click blank then click option'
Amodel
Bself.model
C@model
D$model
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access the variable without @.
Using global variable syntax ($) instead of instance variable (@).
3fill in blank
hard

Fix the error in the code by completing the instance variable assignment.

Ruby
class Book
  def initialize(title)
    [1] = title
  end

  def title
    @title
  end
end
Drag options to blanks, or click blank then click option'
A@title
Btitle
C$title
Dself.title
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning to a local variable instead of an instance variable.
Using global variable syntax ($) instead of instance variable (@).
4fill in blank
hard

Fill both blanks to create a method that updates and returns an instance variable.

Ruby
class User
  def initialize(age)
    @age = age
  end

  def birthday
    @age [1] 1
    return [2]
  end
end
Drag options to blanks, or click blank then click option'
A+=
B-=
C@age
Dage
Attempts:
3 left
💡 Hint
Common Mistakes
Using -= instead of +=.
Returning a local variable instead of the instance variable.
5fill in blank
hard

Fill all three blanks to define an instance variable, update it, and return it.

Ruby
class Counter
  def initialize(start)
    [1] = start
  end

  def increment
    [2] [3] 1
    return @count
  end
end
Drag options to blanks, or click blank then click option'
A@count
B+=
C-=
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning to a local variable instead of an instance variable.
Using -= instead of +=.
Trying to update a variable without @.