我如何计算该输入之前和之后的整数数量。
user_array = user_input.chars.to_a
user_array.map {|item| item.to_i}
num = gets.to_i
arrange_array = user_array.push(num).join(",")
#need to give number before, and number after input
puts "Please enter some numbers:"
user_input = gets.chomp
puts "Please enter another number:"
num = gets.to_i
user_input.split('')
.map(&:to_i) # convert them to integers
.partition { |n| n < num } # split / partition by cond
.map(&:sort) # sort results
#⇒ [[0, 1, 2], [4, 5]]
该解决方案的核心是Enumerable#partition
方法,该方法按提供的条件拆分数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句