我想比较两个散列和力量他们是平等的:比较两个哈希不管符号或字符串,轨道
- 一个与键符号和值
- 第二用只有字符串。
如:
sym_hash = {:id=>58, :locale=>:"en-US"}
string_hash = {"id"=>58, "locale"=>"en-US"}
尝试这样不起作用:
> sym_hash == string_hash
=> false
我第一次尝试象征的string_hash
:
> string_hash.deep_symbolize_keys
=> {:id=>58, :locale=>"en-US"}
,但它仍然是假b因为sym_hash
仍然有:
前locale
变种。
然后我试图字符串化的sym_hash
:
> sym_hash.with_indifferent_access
=> {"id"=>58, "locale"=>:"en-US"}
但是,当我测试的平等仍然是false
出于同样的原因。
编辑
要回答很多评论abouy 为什么我想这些哈希等于在这里,我将解释什么,我试图做的。
我使用Reque
来管理我的工作。现在我想做一个班级,以避免同一个*作业正在运行,或者在同一时间内两次入队。
(相同:对我来说,同样的工作是具有相同参数的工作,我希望能够有enqueu两次型动物同样的工作IDS的实例。)
对于我使用插件resque-status
,到目前为止,我可以知道工作是否正在运行。除此之外,当我使用set
保存参数时,我注意到写入Redis
的消息(因为resis-status正在使用Redis来跟踪作业的状态)未正确保存为符号。
这里是我的类:
# This class is used to run thread-lock jobs with Resque.
#
# It will check if the job with the exact same params is already running or in the queue.
# If the job is not finished, it will returns false,
# otherwise, it will run and returns a the uuid of the job.
#
class JobLock
def self.run(obj, params = {})
# Get rid of completed jobs.
Resque::Plugins::Status::Hash.clear_completed
# Check if your job is currently running or is in the queue.
if !detect_processing_job(obj, params)
job_uuid = obj.create(params)
Resque::Plugins::Status::Hash.set(job_uuid,
job_name: obj.to_s,
params: params)
job_uuid
else
false
end
end
def self.detect_processing_job(obj, params = {})
Resque::Plugins::Status::Hash.statuses.detect do |job|
job['job_name'] == obj.to_s && compare_hashes(job['params'], params)
end
end
def self.compare_hashes(string_hash, sym_hash)
[sym_hash, string_hash].map do |h|
h.map { |kv| kv.map(&:to_s) }.sort
end.reduce :==
end
end
在这里,我如何使用它:
JobLock.run(MyAwesomeJob, id: 58, locale: :"en-US")
正如你可以看到我用@ mudasobwa的答案,但我希望有一个更简单的方法来实现我正在尝试做什么!下面
这些散列*** ***有不同 –
是,在这种情况下,我想修改它们以使它们相似 –
它不是一行代码(除非将它包装在方法中),但是您可以遍历哈希值并根据它们的'to_s'方法比较值。如果需要,我可以提供代码示例。 – MrDanA