Ruby - 用户输入整数数组的问题
我正在尝试接受两个整数的输入,以空格分隔: 3 5
并将其保存到整数数组中。我这样做了 3 次,但我在将其从字符串转换为整数时遇到问题。这是我的循环:
for i in 1..3
puts "What is point " + i.to_s + " ?" # asks for input
s.push gets.split(" ")
end
然后,我想让
if s[1][0] - s[0][0] = 0
blah blah blah
end
数组 s
当前看起来像
------------
| "1" "2" |
| "3" "4" |
| "5" "6" |
------------
我希望它看起来像
--------
| 1 2 |
| 3 4 |
| 5 6 |
--------
我已经尝试过 gets.split(" ").map { |s| s.to_i }
和 gets.split(" ").collect{|i| i.to_i}
但我意识到我应该问这里的人。
我刚刚开始学习 Ruby,所以如果您不介意对解决方案进行简短的解释,我将非常感激:)
谢谢!
注意:这与 这个问题,我确实尝试在循环后使用 .collect
和 .map
,但仍然不起作用。
I am trying to accept input of two integers, separated by a space: 3 5
and save that into an integer array. I do this 3 times, but I am having trouble converting this from string to integers. Here is my loop:
for i in 1..3
puts "What is point " + i.to_s + " ?" # asks for input
s.push gets.split(" ")
end
Then, I want to have
if s[1][0] - s[0][0] = 0
blah blah blah
end
The array s
currently looks like
------------
| "1" "2" |
| "3" "4" |
| "5" "6" |
------------
I want it to look like
--------
| 1 2 |
| 3 4 |
| 5 6 |
--------
I have tried gets.split(" ").map { |s| s.to_i }
and gets.split(" ").collect{|i| i.to_i}
but I realize I should just ask someone here.
I have just started learning Ruby, so if you don't mind a short explanation with the solution, i would really appreciate it :)
Thanks!
Note: This is pretty much the opposite of this question, and I did try to use .collect
and .map
following the loop, which still did not work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,抱歉,我刚刚看到了错误。我不敢相信我错过了。
在
if
语句中,您使用=
而不是==
。=
分配事物,==
比较事物。完整的工作程序可能如下所示:Okay, sorry, I just saw the mistake. I can't believe I missed that.
In your
if
statement, you are using=
instead of==
.=
assigns things, and==
compares things. A full working program could look like this:你的回答对我来说看起来不错。您可以将 s.push 替换为 s << (更Rubyish)并且不需要 split 的争论。虽然我是新手,但我认为大多数 Rubyiest 都会写:
s << gets.split.map {|x| x.to_i}
另外,您可以替换
put "What is point " + i.to_s + " ?"
与
put“什么是点 #{i} ?”
Your answer looks good to me. You might replace s.push with s << (more Rubyish) and there is no need for split's argument. Though I'm a newbie, I think most Rubyiests would write:
s << gets.split.map {|x| x.to_i}
Also, you could replace
puts "What is point " + i.to_s + " ?"
with
puts "What is point #{i} ?"