在命令提示符中执行代码后Ruby程序退出

问题描述:

为什么程序在命令行中执行后退出?在命令提示符中执行代码后Ruby程序退出

我将下面的代码保存为.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

哪里?请让我知道它在哪里以及是否导致我的问题 – Amir

+0

在最后添加了此项,并且程序没有退出,我能够看到列表: puts“当您完成时按返回。” 得到 – Amir

+2

这种缩进是纯粹的无*状态。如果你更好地组织你的代码并且正确缩进,那么错误会更加明显。 – tadman

我看看你的代码,当过你面对这种运行命令红宝石-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
--------------------------------------------------------------------------------