使用Ruby收集和存储用户输入

时间:2014-09-09 14:55:03

标签: ruby arrays user-input storing-information

我正在开发一个程序,要求用户提供有关最近财务交易的输入,并希望在将用户输入存储到空数组中并在调用时能够显示该信息方面提供一些帮助。现在,空数组(它实际上是一个哈希值)没有收到任何东西。

在编程和Ruby方面,我非常环保,并且非常喜欢任何帮助!

###I want transactions (below) to house user_input so that when a user
###chooses 'display' it will return what the user has input.
transactions = {}

puts "What would you like to do?"
puts "-- Type 'add' to add a transaction."
puts "-- Type 'update' to update a transaction."
puts "-- Type 'display' to display all transactions."
puts "-- Type 'delete' to delete a transaction."

choice = gets.chomp.downcase
case choice
when 'add'
  puts "What transaction would you like to add?"
  user_input = gets.chomp
  if transactions[user_input.to_sym].nil?
    puts "What's the rating? (Type a number 0 to 4.)"
    rating = gets.chomp
    transactions[user_input.to_sym] = rating.to_i
    puts "#{user_input} has been added with a rating of #{rating}."
  else
    puts "That transaction already exists! Its rating is #{transactions[title.to_sym]}."
  end
when 'update'
  puts "What transaction do you want to update?"
  user_input = gets.chomp
  if transaction[title.to_sym].nil?
    puts "Transaction not found!"
  else
    puts "What's the new rating? (Type a number 0 to 4.)"
    rating = gets.chomp
    transactions[title.to_sym] = rating.to_i
    puts "#{user_input} has been updated with new rating of #{rating}."
  end
when 'display'
  transactions.each do |receipt, rating| ###figure out how to change this so that the
    puts "#{receipt}: #{rating}"         ###user's input is returned
  end
when 'delete'
  puts "What transaction do you want to delete?"
  user_input = gets.chomp
  if transactions[user_input.to_sym].nil?
    puts "Transaction not found!"
  else
    transactions.delete(user_input.to_sym)
    puts "#{user_input} has been removed."
  end
else
  puts "Sorry, I didn't understand you."
end

2 个答案:

答案 0 :(得分:1)

如果不考虑用户输入的方式,您可能会发现只是使用错误类型的对象来存储数据。例如,请考虑使用Array Structhighline对象进行以下重写。

require 'pp'

class Transaction < Struct.new(:title, :rating)
end

transactions = []
transactions.push(Transaction.new 'example1', 1)
transactions.push(Transaction.new 'example2', 3.5)

pp transactions

t = transactions.find { |s| s.title == 'example1' }
t.rating = 4

pp transactions

您可以将Transaction扩展为直接征求用户输入,清理成员值,或使用{{3}}之类的内容来创建某种菜单。在我看来,这个细节并不重要,因为能够以明智和一致的方式设置和检索你的Struct成员,但你的里程可能会有所不同。

答案 1 :(得分:0)

以下是http://gistpages.com/2013/07/28/ruby_arrays_insert_append_length_index_remove

的一些信息

您可以使用类似

的内容
transaction = Array.new
user_input = gets.chomp
transaction.insert(user_input)