如何检查哈希中的现有值并关联匹配的值?

问题描述 投票:0回答:2

我正在努力实现以下目标:

我想检查一个艺术家是否已经存在于哈希中,如果是,则将输入的诗歌与指定的艺术家相关联,如下所示。

 hash = [{verse: ['dust in the wind', 'hold on'], artist: kansas, genre: rock}]

我尝试过类似的东西,但我不确定如何将输入的新经文与现有经文联系起来。

if all_verses.any? { |hash| hash[:artist].include?(add_verse[:artist])}
   puts "add_verse[:artist] is quite popular! They are already in our catalog!

这是我到目前为止:

def ask(question)
  puts "#{question}"

  answer = gets.chomp
  return answer
end


def add_verse
  hash = {verse: [''], artist: '', genre: ''}

  hash[:verse] = ask('What is the verse?')
  hash[:artist] = ask('Who is the artist?')
  hash[:genre] = ask('What is the genre?')

  return hash
 end

all_verses = []

response = ''
while response != 'no'
  all_verses << add_verse
  response = ask('Do you want to add more?')
  end
end

puts all_verses

提前谢谢了!

ruby
2个回答
1
投票

我改变了你的代码,它为同一位艺术家添加了更多的经文。

def ask(question)
    puts "#{question}"
    answer = gets.chomp
    return answer
end

def add_verse
    artist = ask('Who is the artist?')
    verse = ask('What is the verse?')

    @all_verses.each do |item|
        if (item[:artist] == artist)
            item[:verse].push(verse)
            return
        end
    end

    genre = ask('What is the genre?')
    @all_verses << { verse: [verse], artist: artist, genre: genre }
end

@all_verses = []
response = ''

while response != 'no'
    add_verse
    response = ask('Do you want to add more?')
end

puts @all_verses

1
投票

我相信这可以用更优雅和干燥的方式进行重构,但是现在这是我解决问题的方法。如果一个艺术家已经存在,那么新的诗歌将被添加到其经文数组中(并且不再要求该类型,因为它应该是相同的),否则它会创建一个新的条目。

def ask(question)
 puts "#{question}"
 answer = gets.chomp
 return answer
end

@all_verses = []

def add_verse
  hash = {verse: [], artist: '', genre: ''}

  @artist = ask('Who is the artist?')

  if @all_verses.length >0
    if @all_verses.any?{|hash| hash[:artist] == @artist}
      @all_verses.each do |h|
         if h[:artist] == @artist
           h[:verse] << ask('What is the verse?')
         end
      end
    else
        hash[:artist] = @artist
        hash[:verse] << ask('What is the verse?')
        hash[:genre] = ask('What is the genre?')
        @all_verses << hash
    end
  else
    hash[:artist] = @artist
    hash[:verse] << ask('What is the verse?')
    hash[:genre] = ask('What is the genre?')
    @all_verses << hash
  end 
end


response = ''
while response != 'no'
  add_verse
  response = ask('Do you want to add more?')
end

puts @all_verses.inspect
© www.soinside.com 2019 - 2024. All rights reserved.