开发者

Ruby - problems with user input to integer array

开发者 https://www.devze.com 2023-01-09 00:39 出处:网络
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

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开发者_JAVA技巧 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.


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 = []
for i in 1..3
    puts "What is point " + i.to_s + " ?"    # asks for input
    s.push gets.split(" ").map {|x| x.to_i }
end
if s[1][0] - s[0][0] == 0 # notice the '=='.
    puts 'It worked!'
end


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} ?"

0

精彩评论

暂无评论...
验证码 换一张
取 消