我有一个类,在它的方法中产生一个哈希的输出。 => {“A”=>“1”,“B”=>“2”}
我的问题是如何将这个产生的哈希发送到另一个类,并使用进一步处理此哈希数据的方法?
我已经阅读了ruby文档并在StackOverflow上进行了搜索,但似乎无法弄清楚如何让这个新类获取这些数据(来自原始类)。 在尝试调用第一个类的方法时,我在第二个类中遇到“未定义的局部变量或方法”错误。
感谢您的帮助。 希望我在我的问题上提供足够的背景知道某人可以提供一些指导。
EDIT--
这是我的代码,它产生了上面提到的哈希。实际上在这个阶段它是一个阵列。
理想情况下,我希望将build_list
方法中的所有代码放在一个完全独立的类中。这样做需要我将生成的数组数据(从用户输入)传递给这个新类中的其他方法。在这个新课程中,我希望打印完成的播放列表。所以我想将这个示例代码吐成两个类,第二个类对用户提供的艺术家进行所有处理工作。我希望这更清楚。
require 'lib/uri.rb'
require 'json'
require 'rest_client'
require 'colorize'
class Playlist
attr_accessor :artistInput, :artist_list
def initialize
@artistInput = artistInput
@artist_list = []
@artist = @artist
end
def self.start #welcome to the application + rules
puts "-------------------------------------------------------------------------------------------------------------------"
puts "|This Playlist Creator application will create you a static playlist from a given list of artists supplied by you.|".colorize(:color => :white, :background => :black)
puts "-------------------------------------------------------------------------------------------------------------------"
puts "Hint: To stop adding artists, type '\N\' + the [enter] key at any time."
# puts "Hint: For artists with spaces, eg \'Lady Gaga\' - please remove the spaces and write as such \'LadyGaga\'."
end
system "clear"
def artistInput #loop that creates an artist_list array of an infinate amount of artists, stops at the keyword 'N'
@artist_list = []
while @artist != ""
puts "\nWhat artist would you like to add to the Playlist?"
@artist = gets.gsub(/\s+/, "")
if @artist != 'N'
puts "You have chosen to add #{@artist} to the Playlist."
end
break if @artist =~ /N/
@artist_list << @artist.gsub(/\s+/, "") #.gsub removes spaces. 'Lady Gaga' => 'LadyGaga'
end
def build_list
#@artist_list
list = @artist_list
list.join('&artist=')
end
def build_url_string
string = build_list
url = 'http://developer.echonest.com/api/v4/playlist/static?api_key=G3ABIRIXCOIGGCCRQ&artist=' + string
end
system "clear"
def parse_url
url = build_url_string
response = JSON.parse(RestClient.get url)
song = response['response']['songs'].each do |song|
song.delete("artist_id")
song.delete("id")
puts
song.each {|key, value| puts "#{key.colorize(:white)}: \'#{value.colorize(:color => :white, :background => :black)}\'" }
end
# a = response['response']['songs']
# a.fetch('id')
end
a = parse_url
puts "\nThere are #{a.length} songs in this Playlist\n\n"
#Uncomment this section to see the raw data feed
# puts "////////////////raw data hash feed//////////////"
# puts "#{a.to_s}"
end
end
答案 0 :(得分:0)
如果没有代码示例,很难回答你的问题。但是我将尽力使用这个例子
class A
def get_hash
{"A"=>"1", "B"=>"2"}
end
end
class B
def process_hash(hash)
#do something with the hash
end
end
hash = A.new.get_hash
B.new.process_hash(hash)