简体   繁体   English

Ruby-循环使用gets.chomp进行计算

[英]Ruby - calculations with gets.chomp in a loop

I'm very new to Ruby. 我是Ruby的新手。 I've been trying to find a way to do calculations with user inputs. 我一直在尝试找到一种使用用户输入进行计算的方法。 There are two things that I wanted to do: 我想做两件事:

  1. Output which friend has the most dinosaurs or jellyfish. 输出哪个朋友的恐龙或水母最多。
  2. Output which friend has the most dinosaurs and jellyfish combined. 输出哪个朋友的恐龙和水母加起来最多。

I only have this loop requesting for user inputs so far: 到目前为止,我只有这个循环要求用户输入:

f = "yes"

while f == "yes"
print "Enter your name: "
n = gets.chomp.to_f
print "Enter the number of dinosaurs you have: "
d = gets.chomp.to_f
print "Enter the number of jellyfish you have: "
j = gets.chomp.to_f
print "Another friend? (yes/no)"
f = gets.chomp
end

Any help is appreciated. 任何帮助表示赞赏。 Thank you so much! 非常感谢!

UPDATES: Thank you so much for you all's help. 更新:非常感谢您的帮助。 I've realized that I was not specific enough. 我意识到我不够具体。 I'll try to clarify that here. 我会在这里尝试澄清。

The output that I want looks something like this (things in ~ ~ are user inputs): 我想要的输出看起来像这样(〜〜中的内容是用户输入):

Enter your name: ~ Bob~
Enter the number of dinosaur you have: ~3~
Enter the number of jellyfish you have: ~6~
Another friend? (yes/no) ~yes~
Enter your name: ~ Sally~
Enter the number of dinosaur you have: ~2~
Enter the number of jellyfish you have: ~8~
Another friend? (yes/no) ~no~
Friend who has the most dinosaurs: Bob
Friend who has the most jellyfish: Sally
Friend who has the most dinosaurs and jellyfish combined: Sally

So far, the codes that I wrote only gets me to "Another friend? (yes/no)" but I'm not sure how to ask Ruby to output the last three lines that I want. 到目前为止,我编写的代码仅使我进入“另一个朋友?(是/否)”,但是我不确定如何要求Ruby输出我想要的最后三行。 Can you folks shed some light on this, please? 请大家对此有所启发吗?

Thank you very much! 非常感谢你!

MORE UPDATES: Thanks for all of your help! 更多更新:感谢您的所有帮助! Got it figured out with Hash and Array. 用Hash和Array弄清楚了。 Thank you! 谢谢!

The answer to your question is three-fold. 您的问题的答案有三点。

Collecting user input 收集用户输入

gets returns a line from stdin, including the newline. gets从stdin返回一行,包括换行符。 If the user enters B o b enter then gets returns "Bob\\n" . 如果用户输入B o b enter,gets返回"Bob\\n"

To strip the newline you use String#chomp : 要剥离换行符,请使用String#chomp

"Bob\n".chomp #=> "Bob"

To convert an input like "3\\n" to an integer 3 , you can use String#to_i : 要将"3\\n"类的输入转换为整数3 ,可以使用String#to_i

"3\n".to_i #=> 3

Note that to_i ignores extraneous characters (including newline), so you can avoid chomp . 请注意, to_i忽略多余的字符(包括换行符),因此可以避免使用chomp

Storing data 储存资料

You probably want to store a user's data in one place. 您可能希望将用户数据存储在一个地方。 In an object-oriented programming language like Ruby, such "place" is often a class. 在像Ruby这样的面向对象的编程语言中,这样的“地方”通常是一个类。 It can be as simple as: 它可以很简单:

class User
  attr_accessor :name, :dinosaurs, :jellyfish
end

attr_accessor creates getters and setters, so you can read and write a user's attributes via: attr_accessor创建getter和setter,因此您可以通过以下方式读取和写入用户的属性:

user = User.new
user.name = 'Bob'
user.name #=> "Bob"

Since you don't want just one user, you need another place to store the users. 由于您不希望只有一个用户,因此您需要另一个位置来存储用户。

An Array would work just fine: Array可以正常工作:

users = []

user = User.new
user.name = 'Bob'
user.dinosaurs = 3

users << user

users
#=> [#<User @name="Bob", @dinosaurs=3>]

Adding a second user: 添加第二个用户:

user = User.new     # <- same variable name, but new object
user.name = 'Sally'
user.dinosaurs = 2

users << user

users
#=> [#<User @name="Bob", @dinosaurs=3>, #<User @name="Sally", @dinosaurs=2>]

Retrieving the users (or their attributes) from the array: 从数组中检索用户(或其属性):

users[0]      #=> #<User @name="Bob">
users[0].name #=> "Bob"
users[1].name #=> "Sally"

Calculating with data 用数据计算

Array includes many useful methods from the Enumerable mixin. Array包括Enumerable mixin中的许多有用方法。

To get an element with a maximum value there's max_by – it passes each element (ie user) to a block and the block has to return the value you are interested in (eg dinosaurs ). 要获得具有最大值的元素,请使用max_by –将每个元素(即用户)传递给一个块,该块必须返回您感兴趣的值(例如dinosaurs )。 max_by then returns the user with the highest dinosaurs value: 然后, max_by返回具有最高dinosaurs值的用户:

users.max_by { |u| u.dinosaurs }
#=> #<User @name="Bob">

You can also calculate the value: 您还可以计算值:

users.max_by { |u| u.dinosaurs + u.jellyfish }

But that would currently result in an exception, because we did not set jellyfish above. 但这目前会导致异常,因为我们没有在上面设置jellyfish

Right now you're trying to turn the name into a float (number) by calling to_f on it. 现在,您正在尝试通过调用to_f将其转换为浮点数(数字)。 It's already a string when it's coming in from the user, and should probably stay a string. 当它来自用户时,它已经是一个字符串了,应该保留一个字符串。

Also, you're currently overwriting each of your variables in every iteration of your loop. 另外,您当前正在循环的每次迭代中覆盖每个变量。 So if Bob fills this out, and wants to add a friend, Sally, all of Bob's information is overwritten by Sally's. 因此,如果Bob填写了此信息,并想添加一个朋友Sally,则Bob的所有信息都会被Sally的信息覆盖。

Instead, you'll need to create a Hash or Array, then add each user to it one by one from your loop. 相反,您需要创建一个哈希或数组,然后从循环中将每个用户一个一个地添加到其中。

continue = "yes"
users = {}

while continue == "yes"
print "Enter your name: "
name = gets.chomp.to_f
print "Enter the number of dinosaurs you have: "
dinosaursCount = gets.chomp.to_f
print "Enter the number of jellyfish you have: "
jellyfishCount = gets.chomp.to_f

users[name] = {dinosaurs: dinosaursCount, jellyfish: jellyfishCount}

print "Another friend? (yes/no)"
continue = gets.chomp
end

Now if Bob and Sally have both been added through the command line, you can get their data by doing: 现在,如果Bob和Sally都已通过命令行添加,则可以通过执行以下操作获取它们的数据:

users.Bob #{dinosaurs: 10, jellyfish: 10}
users.Bob.dinosaurs #10
users.Bob.jellyfish #10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM