简体   繁体   English

Ruby在一行中打印两个整数,而无需使用字符串插值

[英]Ruby Print two integers in one line without using string interpolations

I am solving this problem on hacker rank https://www.hackerrank.com/challenges/mini-max-sum/problem 我正在黑客等级https://www.hackerrank.com/challenges/mini-max-sum/problem解决此问题

Its asking: Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. 它的要求是:打印两个以空格分隔的长整数,分别表示可以通过对五个整数中的四个精确求和而得出的最小值和最大值。 (The output can be greater than 32 bit integer.) (输出可以大于32位整数。)

If I am doing string interpolations as in my code below, its giving me an error: Your code did not pass this test case. 如果我按照下面的代码进行字符串插值,则会给我一个错误:您的代码未通过此测试用例。 I know I can't use multiple variables in a single puts/p line. 我知道我不能在单个puts / p行中使用多个变量。

array = gets.split(" ")

def get_max_and_min_sum(input_array)
    return "0 0" if input_array.size < 1

    input_array = input_array.map{|i| i.to_i}

    input_array = input_array.sort

    return "#{sum(input_array[0..3])} #{sum(input_array[1..4])}"



end

def sum(array)
    return array.inject(0){|sum,i| sum+=i}
end

p get_max_and_min_sum(array)

My question is how can I print multiple integers in one line separated by one space. 我的问题是如何在一行中用空格隔开打印多个整数。 I want to print 10 14 and not "10 14" 我想打印10 14而不是“ 10 14”

在此处输入图片说明

Your problem is not in the string interpolation but in the method you use to print out the result to stdout. 您的问题不在于字符串插值,而在于用于将结果打印到stdout的方法。 You should use print or puts instead of p since print and puts call to_s which simply converts to string, while p calls inspect which shows you more information (like the quotes to indicate that it is a string and in other cases stuff like hidden characters) and is more useful for debugging. 您应该使用printputs而不是p因为printputs调用to_s会简单地转换为字符串,而p调用inspect会向您显示更多信息(例如引号表示它是字符串,在其他情况下则是诸如隐藏字符之类的东西)并且对于调试更有用。

As for the difference between print and puts - puts simply inserts a newline at the end while print does not and prints exactly what you give it. 至于printputs之间的区别puts仅在末尾插入换行符,而print不插入换行符,并精确打印您提供的内容。

The issue is the difference between p and print : 问题是pprint之间的区别:

irb(main):003:0> p "1 2"
"1 2"

irb(main):005:0> print "1 2"
1 2

use print and your problem should be solved 使用打印,您的问题应该得到解决

Given 给定

str = "21 4 8 13 11"

compute 计算

arr = str.split.map(&:to_i)
  #=> [21, 4, 8, 13, 11]
smallest, largest = arr.minmax
  #=> [4, 21]
tot = arr.sum
  #=> 57
print "%d %d" % [tot-largest, tot-smallest]
36 53

Change print to puts in the last line if a carriage return is to be printed. 如果要打印回车符,请在最后一行puts print更改为puts

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

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