用用户输入/用最少的代码行填充数组的最简单方法

Cod*_*ncy 1 ruby

从用户输入创建由混合数据类型(即包含字符串,整数和浮点数的数组)组成的x个元素组成的数组的最简单方法是什么

到目前为止,我编写了一些使用for循环的代码,但我想知道是否有一种优化它的方法,并且代码行最少。

puts "how many elements?"

max = gets.to_i
array = []

for i in 0..max - 1
  puts "are you entering in a string, an int or a float?"
  data_type = gets.chomp

  if %W[string STRING String s S].include?(data_type)
    puts "enter in a string"
    array[i] = gets.chomp
  elsif %W[int INT Int i I].include?(data_type)
    puts "enter an int"
    array[i] = gets.to_i
  elsif %W[Float FLOAT float f F].include?(data_type)
    puts "enter a float"
    array[i] = gets.to_f
  end
end

print array
Run Code Online (Sandbox Code Playgroud)

Ama*_*dan 5

最小行数?一。一旦拥有max

array = max.times.map { gets.chomp.then { |l| case l when /^\d+$/ then l.to_i when /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/ then l.to_f else l end } }
Run Code Online (Sandbox Code Playgroud)

这甚至更短(尽管有些人会反对):

array = max.times.map { gets.chomp.then { |l| Integer(l) rescue Float(l) rescue l } }
Run Code Online (Sandbox Code Playgroud)

但是,将其写成几行会更易读。

还要注意,Rubyists基本上假装for该语言不存在,并且通常会用Enumerable#eachInteger#times和类似语言代替它。


这与您所拥有的并不完全相同;我的代码无法使字符串成为有效数字,例如"2.0"。如果您想要该功能,您的代码也不会太糟糕(通常误导行数)。我会改变的事情:

  • 环。array = max.times.map do ... endfor任何时候。(这也使得array[i]没有必要明确分配。)

  • "float".start_with?(data_type.downcase)而不是%W[Float FLOAT float f F].include?(data_type),因此您无需担心列出所有变体。

  • _“ Rubyists基本上假装不存在” _ –您在说的`for`是什么? (5认同)