简体   繁体   中英

how to set two instance variables to each other in Ruby

I'm working on Chris Pine's Ruby tutorial. I have to write a cheat method that allows me to set which side of the die I want to show: https://pine.fm/LearnToProgram/?Chapter=09

I have two instance variables: @numberShowing and @numberCheat. @numberCheat receives an input from the user and I want to set @numberShowing to take the value of @numberCheat. However, @numberShowing always outputs some random number. Any tips?

Here's my code so far:

class Die
    def initialize
        roll
    end

    def roll
        @numberShowing = 1 + rand(6)
    end

    def showing
        @numberShowing
    end

    def cheat
        puts "cheat by selecting your die number between 1 and 6"
        @numberCheat = gets.chomp
    end
    @numberShowing = @numberCheat
end
puts Die.new.cheat
puts Die.new.showing

Thanks!

Move @numberShowing = @numberCheat into the cheat method. But your test is not going to prove it worked. Try something like:

die = Die.new
puts "Currently showing #{die.showing}"
puts "Cheating to change showing number to #{die.cheat}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM