【问题标题】:how to set two instance variables to each other in Ruby如何在 Ruby 中设置两个实例变量
【发布时间】:2014-07-08 21:46:13
【问题描述】:

我正在编写 Chris Pine 的 Ruby 教程。我必须写一个作弊方法,让我可以设置我想展示骰子的哪一面:https://pine.fm/LearnToProgram/?Chapter=09

我有两个实例变量:@numberShowing 和@numberCheat。 @numberCheat 接收来自用户的输入,我想设置@numberShowing 以获取@numberCheat 的值。但是,@numberShowing 总是输出一些随机数。有什么建议吗?

到目前为止,这是我的代码:

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

谢谢!

【问题讨论】:

  • 你应该在某个方法中分配@numberShowning,而不是在类本身中。

标签: ruby class methods instance-variables


【解决方案1】:

@numberShowing = @numberCheat 移动到cheat 方法中。但是你的测试并不能证明它有效。尝试类似:

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

【讨论】:

  • 谢谢克里斯!这行得通。之后我什至放了另一行: puts die.showing 来测试它,显示数字取作弊号的值。你能向我解释一下它是如何工作的吗?谢谢
猜你喜欢
  • 2010-10-24
  • 2018-03-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-07
  • 1970-01-01
  • 2011-01-09
  • 2016-08-22
  • 1970-01-01
相关资源
最近更新 更多