1

最近の金融取引に関する入力をユーザーに求めるプログラムに取り組んでおり、ユーザー入力を空の配列に格納し、呼び出されたときにその情報を表示できるようにするための助けが必要です。現在、空の配列 (現時点では実際にはハッシュ) は何も受け取りません。

プログラミングと 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
4

2 に答える 2

1

ユーザー入力を取得する方法は別として、データを格納するために間違ったタイプのオブジェクトを使用しているだけであることに気付くかもしれません。たとえば、Structオブジェクトの配列を使用した次の書き換えを考えてみましょう。

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 を拡張して、ユーザー入力を直接要求したり、メンバー値をサニタイズしたり、ハイラインなどを使用して何らかのメニューを作成したりできます。私の意見では、これの詳細は、賢明で一貫した方法で構造体のメンバーを設定および取得できるほど重要ではありませんが、マイレージは異なる場合があります。

于 2014-09-09T16:09:42.570 に答える