为什么程序在命令行中执行后退出?
我将下面的代码保存为.rb文件。当我运行它时,它会遍历所有内容,但它不会向我显示我想要查看的结果哈希。相反,程序退出。
def create_list
print "What is the list name? "
name=gets.chomp
hash={"name"=>name,"items"=>Array.new}
return hash
end
def add_list_item
print "What is the item called? "
item_name=gets.chomp
print "How much? "
quantity=gets.chomp.to_i
hash={"name"=>item_name, "quantity"=>quantity}
return hash
end
def print_separator(character="-")
puts character *80
end
def print_list(list)
puts "List: #{list['name']}"
print_separator()
list["items"].each do |item|
puts "\tItem: " + item['name'] + "\t\t\t" +
"Quantity: " + item['quantity'].to_s
end
print_separator()
end
list=create_list()
list['items'].push(add_list_item())
list['items'].push(add_list_item())
puts "Here is your list: \n"
print_list(list)
答案 0 :(得分:1)
我看了你的代码,我建议当你遇到这种问题时运行命令ruby -wc file_name.rb,这就是打印出来的:
list.rb:22: warning: *' after local variable or literal is interpreted as binary operator
list.rb:22: warning: even though it seems like argument prefix
list.rb:24: warning: mismatched indentations at 'end' with 'def' at 21
list.rb:38: warning: mismatched indentations at 'end' with 'def' at 27
Syntax OK
因此,在修复缩进之后,您需要解决的下一件事是print_separator方法:
def print_separator(character="-")
puts character *80
end
将其更改为:
def print_separator()
80.times do |n|
print "-"
end
puts
end
这也是相同代码的工作版本:
def create_list
print "What is the list name? "
name=gets.chomp
hash={"name"=>name,"items"=>Array.new}
return hash
end
def add_list_item
print "What is the item called? "
item_name=gets.chomp
print "How much? "
quantity=gets.chomp.to_i
hash={"name"=>item_name, "quantity"=>quantity}
return hash
end
def print_separator()
80.times do |n|
print "-"
end
puts
end
def print_list(list)
puts "List: #{list['name']}"
print_separator()
list["items"].each do |item|
puts "\tItem: " + item['name'] + "\t\t\t" +
"Quantity: " + item['quantity'].to_s
end
print_separator()
end
list=create_list()
list['items'].push(add_list_item())
list['items'].push(add_list_item())
puts "Here is your list: \n"
print_list(list)
输出:
What is the list name? My list
What is the item called? apple
How much? 2
What is the item called? orange
How much? 2
Here is your list:
List: My list
--------------------------------------------------------------------------------
Item: apple Quantity: 2
Item: orange Quantity: 2
--------------------------------------------------------------------------------