在本文中,我们将研究Hash.replace()方法。可以借助其名称来预测此方法的工作,但是它并不像看起来那样简单。好吧,我们将在其余内容中借助其语法和程序代码来理解此方法。
方法说明:
此方法是在ruby库中定义的公共实例方法,特别是针对Hash类。由于此方法是破坏性方法的示例,因此此方法创建的更改是永久的或非临时的。此方法的工作方式是将当前哈希的内容替换为在其上已调用该方法的哈希的内容。
语法:
Hash_object.replace(other_hash)
Argument(s) 需要:
此方法仅使用一个参数,而该参数则是您要存储在主哈希中的内容的另一个哈希。
范例1:
=begin
Ruby program to demonstrate replace method
=end
hsh = Hash.new()hsh["color"] = "Black"
hsh["age"] = 20
hsh["school"] = "Angels' Academy Haridwar"
hsh["college"] = "Graphic Era University"
puts "Hash contents before replace method are : #{hsh}"
hsh2 = {"name"=>"Hrithik","class"=>"bca","age"=>20}
puts "Hash replace implementation"
puts "#{hsh.replace(hsh2)}"
puts "Hash contents after replace method are : #{hsh}"输出结果
Hash contents before replace method are : {"color"=>"Black", "age"=>20, "school"=>"Angels' Academy Haridwar", "college"=>"Graphic Era University"}
Hash replace implementation
{"name"=>"Hrithik", "class"=>"bca", "age"=>20}
Hash contents after replace method are : {"name"=>"Hrithik", "class"=>"bca", "age"=>20}说明:
在上面的代码中,您可以看到我们可以借助Hash将一个哈希的内容替换为另一个哈希对象的内容。replace()方法。您可能会注意到,可以在调用该方法时将散列对象与该方法一起传递。该方法在哈希对象上创建永久更改。
范例2:
=begin
Ruby program to demonstrate replace method
=end
hsh = Hash.new()hsh["color"] = "Black"
hsh["age"] = 20
hsh["school"] = "Angels' Academy Haridwar"
hsh["college"] = "Graphic Era University"
puts "Hash replace implementation"
puts "Hash contents before replace method are : #{hsh}"
puts "#{hsh.replace({"name"=>"Hrithik","class"=>"bca","age"=>20})}"
puts "Hash contents after replace method are : #{hsh}"输出结果
Hash replace implementation
Hash contents before replace method are : {"color"=>"Black", "age"=>20, "school"=>"Angels' Academy Haridwar", "college"=>"Graphic Era University"}
{"name"=>"Hrithik", "class"=>"bca", "age"=>20}
Hash contents after replace method are : {"name"=>"Hrithik", "class"=>"bca", "age"=>20}说明:
在上面的代码中,您可以看到我们可以借助Hash将一个哈希的内容替换为另一个哈希对象的内容。replace()方法。您可能会注意到,在调用该方法时,可以使用该方法传递多个键和值。该方法在哈希对象上创建永久更改。