为什么 rand(variable) 会停止我的 Shoes 程序的执行?
我是鞋子的新手,我正在尝试创建一个简单的骰子滚筒,允许用户通过输入面数来选择自定义尺寸的骰子。我的代码如下:
Shoes.app :width => 500, :height => 300 do
flow do
para "Sides: "
@sides = edit_line
end
flow do
button "Roll!" do
@total = 1 + rand(sides)
alert @total
end
end
end
我在编辑行中输入一个数字,单击按钮,但没有任何反应。
如果我将 @total = rand(sides)
替换为 @total = rand(20)
,程序执行得很好,但当然只会产生 1-20 之间的随机数。
我尝试了像 rand(@sides)
这样的变体,但没有成功。
我用纯 Ruby 设计了一个类似的程序,它使用 rand(sides)
没有任何问题,但如果我尝试在 Shoes 中这样做,它什么也不做。
I am brand new to Shoes, and am trying to create a simple dice roller that allows the user to choose a custom-sized die by inputting the number of sides. My code is as follows:
Shoes.app :width => 500, :height => 300 do
flow do
para "Sides: "
@sides = edit_line
end
flow do
button "Roll!" do
@total = 1 + rand(sides)
alert @total
end
end
end
I input a number in the edit line, click the button, and nothing happens.
If I replace @total = rand(sides)
with @total = rand(20)
, the program executes just fine, but of course only produces random numbers from 1-20.
I tried variations like rand(@sides)
, to no avail.
I designed a similar program in just plain Ruby which uses rand(sides)
without a problem, but if I try to do it in Shoes, it does nothing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你有几个错误。首先,使用
@sides
,而不是sides
。这样,您就可以引用之前设置的同一变量。其次,
@sides
的类型是Shoes::EditLine
。这很好,因为您需要动态查找文本。当您需要@sides
的文本时,调用@sides.text
,它返回一个String
。当然,在这种情况下,您需要将其转换为适合输入到rand
的整数,因此您将使用@sides.text.to_i
。(当然,标准的不信任用户警告适用。实际上,您需要检查输入是否无效并执行一些有用的操作。)
长话短说,替换
@total = 1 + rand (sides)
与@total = 1 + rand(@sides.text.to_i)
就可以了。You have a couple mistakes. First, use
@sides
, notsides
. That way, you're referencing the same variable you set earlier.Second, the type of
@sides
isShoes::EditLine
. Which is good, since you need to look up the text dynamically. When you want the text of@sides
, call@sides.text
, which returns aString
. Of course, in this context, you'll need to convert that to an integer suitable for input torand
, so you'll use@sides.text.to_i
.(Of course, the standard don't-trust-users caveats apply. In reality, you'll want to check your input for invalid input and do something useful.)
Long story short, replace
@total = 1 + rand(sides)
with@total = 1 + rand(@sides.text.to_i)
and you'll be good.edit_line
返回一个 String 对象。您需要先使用@sides = edit_line.to_i
将其转换为整数edit_line
returns a String object. You need to convert it to integer first with@sides = edit_line.to_i