简体   繁体   English

基本的Ruby gets.chomp

[英]Basic Ruby gets.chomp

I'm new to programming and I'm trying to answer this basic question. 我是编程的新手,正在尝试回答这个基本问题。

Write a program which asks for a person's favorite number. 编写一个程序,询问一个人的最爱号码。 Have your program add one to the number, then suggest the result as a bigger and better favorite number. 让您的程序在数字上加一个,然后建议结果是一个更大更好的数字。

This is what I have to far, but it won't convert to a number. 这是我必须要做的,但是不会转换为数字。

    puts "What is your favorite number?"
    number = gets.chomp
    number = number.to_i + 1
    puts "I suggest " + number + " as a bigger and better number"

Look more closely at the error you get: 仔细看看您得到的错误:

What is your favorite number?
42
number.rb:4:in `+': can't convert Fixnum into String (TypeError)
    from number.rb:4:in `<main>'

Line 4 is: 第4行是:

puts "I suggest " + number + " as a bigger and better number"

The problem is that Ruby won't implicitly convert number into a string (eg "foo" + 42 is not valid in Ruby). 问题在于Ruby不会将number隐式转换为字符串(例如, "foo" + 42在Ruby中无效)。 There are a couple of solutions: 有两种解决方案:

  1. Call to_s on number to convert it to a string before concatenating: 调用to_s on number可以在连接之前将其转换为字符串:

     puts "I suggest " + number.to_s + " as a bigger and better number" 
  2. Use Ruby string interpolation : 使用Ruby字符串插值

     puts "I suggest #{number} as a bigger and better number" 

Option 2 is more idiomatic, I suggest using that. 选项2更惯用,我建议使用。

As in many other problems in ruby there are a lot of ways to do it....without the three solutions writed above there is two more: 就像在红宝石中的许多其他问题一样,有很多方法可以实现它。...没有上面写的三种解决方案,还有两种:

puts "What is your favorite number?"
number = gets.chomp.to_i
puts "I suggest %d as a bigger and better number" % [number + 1]

and one wich is almost the same: 和一个几乎是相同的:

puts "What is your favorite number?"
number = gets.chomp.to_i
num = number + 1
puts "I suggest %d as a bigger and better number" % [num]

You can do it this way: 您可以这样操作:

print 'What is your favorite number? '
number = gets.chomp
puts "I suggest #{number.to_i + 1} as a bigger and better number"

There is not to much to explain about the code, but there are few things to take into account: 关于代码,没有太多要解释的东西,但是要考虑的东西很少:

  1. If you are rendering plain text use 'text' instead of "text" . 如果要呈现纯文本,请使用'text'而不是"text" "In the double-quoted case, Ruby does more work. First, it looks for substitutions (sequences that start with a backslash character) and replaces them with some binary value" - Programming ruby 1.9.3 “在双引号的情况下,Ruby会做更多的工作。首先,它查找替换(以反斜杠字符开头的序列),并用一些二进制值替换它们”-编程ruby 1.9.3
  2. Always try to reduce the number of lines of code. 始终尝试减少代码行数。

This things are really insignificant here, but when you are coding a big program, web page etc., it really makes a difference. 这件事在这里确实无关紧要,但是当您编写大型程序,网页等代码时,确实会有所作为。

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

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