Сбор и хранение пользовательского ввода с Ruby

Я работаю над программой, которая запрашивает у пользователя информацию о последних финансовых транзакциях, и мне нужна помощь по сохранению пользовательского ввода в пустом массиве и возможности отображения этой информации при вызове. Прямо сейчас пустой массив (на самом деле это хэш) ничего не получает.

Я невероятно зелен, когда дело доходит до программирования и 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 ответа

Решение

Если не учитывать, как вы получаете пользовательский ввод, вы можете обнаружить, что вы просто используете неправильный тип объекта для хранения ваших данных. Например, рассмотрим следующую перезапись с использованием массива объектов 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, чтобы напрямую запрашивать ввод данных пользователем, очищать значения элементов или использовать что-то вроде highline для создания какого-либо меню. На мой взгляд, детали этого на самом деле не так важны, как возможность устанавливать и извлекать элементы вашей структуры разумным и последовательным образом, но ваш пробег может отличаться.

Вот некоторая информация об этом http://gistpages.com/2013/07/28/ruby_arrays_insert_append_length_index_remove

Вы можете использовать что-то вроде

transaction = Array.new
user_input = gets.chomp
transaction.insert(user_input)
Другие вопросы по тегам