2012-05-26 13 views
2

我的方法得到整數數組高效/直線前進的方式來從stdin在紅寶石

  • GET數組元素作爲字符串的分隔符,如空間或逗號
  • 分割字符串
  • 每個元素轉換成數並推入陣列

的代碼看起來是這樣的:

puts 'Enter array elements with a space' 
array_as_string = gets 
if array_as_string.length > 0 
    input_array = [] 
    array_as_string.split(' ').each { |x| input_array.push(x.to_i) } 
else 
    puts 'Invalid input' 
end 

有沒有更好的/有效的替代方法或直接的方法?

回答

3

split的默認參數是空格。 做的習慣用法 東西與數組中的每個元素並得到一個數組作爲結果 是map

puts "Enter array elements with a space" 
array_as_string = gets 
array = array_as_string.split.map(&:to_i) 
+0

謝謝!學習了一個新的含糖快捷方式:) – mssrivatsa