繁体   English   中英

在 Ruby gem cli 中列出

[英]List in Ruby gem cli

我正在制作一个 ruby​​ cli,它输出从网站上抓取的游戏交易列表。

该列表立即使用

def games_sales
  Deal.all.each_with_index do |deal, index|
    puts "#{index + 1}.  #{deal.title}"
  end 

  puts "What game do you want to see?"
  input = gets.strip

  game_selection(input.to_i)
end

当要求用户从列表中选择一个项目时,我的问题就出现了。

def game_selection(input) 
  deal = Deal.find_by_index(input)
  #binding.pry
  deal.each do |deal| 
    puts "#{deal.index}"
    puts " Name: #{deal.title}" 
    puts " Price: #{deal.price}"
    puts " Store: #{deal.store}"
    puts " Expiration: #{deal.expiration}"
  end 
  deal
end 

它每次都返回 int 输入,但只返回列表中的第一项。

我忘记了 find_by_index 方法:

def self.find_by_index(input)
  all.select do |deal|

  end
end 

这是不完整的

不能 100% 确定我是否正确回答了您的问题以及您是否使用 Rails,但Deals.all让我想到了这一点。

我不得不用 DEALS 替换 Deals.all 进行测试,因为我还没有运行 rails 应用程序。 所以我使用了一组 OpenStructs 来伪造你的模型结果。

# this fakes Deals.all
require 'ostruct' 
DEALS = [
    # add any more properties the same way as title, separated by comma
    OpenStruct.new(title: 123),
    OpenStruct.new(title: 456) 
]

def games_sales
  DEALS.each_with_index do |deal, index|
    puts "#{index + 1}.  #{deal.title}"
  end 

  puts "What game do you want to see?"
  input = gets.strip

  game_selection(input.to_i)
end

def game_selection(input) 
  deal = DEALS.at(input-1)
  p deal[:title]
end 

def self.find_by_index(input)
  all.select do |deal|
    deal.index == input
  end
end 

games_sales

选择1时的结果是123 ,选择2您将得到456 ,这是由于代码中的p deal[:title]

我认为您的 find_by_index 需要获得正确的索引,在我的示例中,我必须使用at(index)作为at(input-1)才能获得正确的结果。

我真的希望这会有所帮助,我建议您将预期结果添加到您的问题中,以防我的回答对您没有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM