if File.exist?("restaurant.txt") then
newfile=File.open("restaurant.txt","r")
lines=newfile.readlines
i=0
while i<lines.size
item=lines[i]
i+=1
quantity=lines[i].to_i
i+=1
price=lines[i].to_i
i+=1
sub=quantity*price
puts sub
end
end
我正在尝试将子值移动到数组
答案 0 :(得分:0)
只需创建一个数组并推送值。
array = Array.new
if File.exist?("restaurant.txt") then
newfile = File.open("restaurant.txt","r")
lines = newfile.readlines
i=0
while i < lines.size
item = lines[i]
i += 1
quantity = lines[i].to_i
i += 1
price = lines[i].to_i
i += 1
sub = quantity*price
#puts sub
array.push(sub)
end
puts array.to_s
end
答案 1 :(得分:0)
使用File#readlines
,数组切片,数组解构和断言前置条件而不是使用if
语句,此代码可以简化如下:
#!/usr/bin/env ruby
FILENAME = 'restaurant.txt'
raise "#{FILENAME} does not exist" unless File.file?(FILENAME)
lines = File.readlines(FILENAME).map(&:chomp)
subs = lines.each_slice(3).map do |slice|
_item, quantity, price = slice
_item = _item.to_i # _item is unused, but this is here for completeness
quantity = quantity.to_i
price = price.to_f
quantity * price
end
p subs
此外,价格,甚至数量应该是浮点数而不是整数。