1,105,177 Community Members

how to get input after space instead of \n

Member Avatar
fk123
Newbie Poster
2 posts since Jan 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 
a=gets.to_i
b=gets.to_i

this code gets input like this
2
2
but in c++ std::cin will get input after space or \n
So how do I make ruby get input like std::cin
I am new to ruby and can not find the answer on google so help would be appreciated thanks

Member Avatar
L7Sqr
Veteran Poster
1,006 posts since Feb 2011
Reputation Points: 179 [?]
Q&As Helped to Solve: 168 [?]
Skill Endorsements: 11 [?]
 
0
 

You could always just get the entire line and split it up by spaces:

line = gets
return unless line
line.chomp.split(/\s+/).each do |token|
   puts "Token: #{token}"
end

which will give you something like:

1 2 3 4 5 # this is the input
Token: 1
Token: 2
Token: 3
Token: 4
Token: 5
Member Avatar
fk123
Newbie Poster
2 posts since Jan 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

thanks

Question Answered as of 2 Years Ago by L7Sqr
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: