Ruby:在另一个哈希中包含一个哈希

时间:2012-05-14 21:58:16

标签: ruby hash

我有以下哈希:

EMAIL_PWD_HASH = Hash.new
EMAIL_PWD_HASH[ "email" ] =  { "label" => EMAIL_STR, "type" => "email_field" }
EMAIL_PWD_HASH[ "password" ] = { "label" => PWD_STR, "type" => "password_field" }

以及以下哈希:

NEW_USER_HASH = Hash.new
NEW_USER_HASH[ "first" ] = { "label" => FIRST_STR, "type" => "text_field" }
NEW_USER_HASH[ "last" ] =  { "label" => LAST_STR, "type" => "text_field" }

NEW_USER_HASH[ "title" ] =  { "label" => TITLE_STR, "type" => "text_field" }
NEW_USER_HASH[ "bio" ] =  { "label" => BIO_STR, "type" => "text_field" }

我想在最后和之前添加电子邮件和密码到NEW_USER_HASH。添加EMAIL_PWD_HASH的语法是什么(顺序很重要)?

2 个答案:

答案 0 :(得分:1)

NEW_USER_HASH.merge!(EMAIL_PAD_HASH)

另请注意,ruby中的哈希值不是有序的。

答案 1 :(得分:0)

我不知道如何做你所问的,我怀疑这是可能的,但这是一种快速和肮脏的方式来做你需要的事情:

NEW_USER_HASH['email']    = EMAIL_PWD_HASH['email']
NEW_USER_HASH['password'] = EMAIL_PWD_HASH['password']
NEW_USER_HASH['bio']      = NEW_USER_HASH.delete('bio')  # deletes bio and reinsert in the end
正如您所问,

emailpassword现在在last之后和bio之前。 :)