从列表中查找Ruby中的负数和POS数字



两个数字列表,一个带有输入pos号的列表,一个与那些是负数的(忽略零值的数字)

方法:在您之前,您必须首先构建两个带有所需输出编号的数组显示其中的任何一个

以下代码不是Ruby。如何将其转换为Ruby?

# Loop to read input and build the two new arrays
while ($next = <>) {
   if ($next > 0) {
      push @pos_list, $next;
   }
   else {
      if ($next < 0) {
         push @neg_list, $next;
      }
   }
}
# Output the results
print "The array of positive numbers: n @pos_list n";
print "nThe array of negative numbers: n @neg_list n";
numbers = [4,-2,7,3,0,-8]
pos_list = numbers.select {|x| x > 0}
neg_list = numbers.select {|x| x < 0}
p pos_list # => [4, 7, 3]
p neg_list # => [-2, -8]

numbers是您从用户输入中构建的数字数组。Array#select返回一个新数组,其中包含所有导致附件块评估true的元素。请参阅:http://www.ruby-doc.org/core-2.1.0/array.html#method-i-select

假设 numbers是输入中的数字:

pos = []
neg = []
numbers.each do |n|
    pos += n if n > 0
    neg += n if n < 0
end

执行以上代码后,您可以从posneg的负面数字中检索正数。

填充numbers的填充方式可能会有所不同。可能的解决方案太循环了,并不断要求一个数字:

numbers = []
begin
    current = gets.chomp.to_i
    numbers << current if current > 0
end until current == 0

假设您不希望0成为number的一部分。否则,您必须检查给定的输入以停止循环。或者,您可以具有固定的数字大小。

最新更新