as_hash ruby
Hash.each_pair方法 (Hash.each_pair Method)
In this article, we will study about Hash.each_pair Method. The working of this method can be predicted with the help of its name but it is not as simple as it seems. Well, we will understand this method with the help of its syntax and program code in the rest of the content.
在本文中,我們將研究Hash.each_pair方法 。 可以借助其名稱來預測此方法的工作,但是它并不像看起來那樣簡單。 好了,我們將在其余內容中借助其語法和程序代碼來理解此方法。
Method description:
方法說明:
This method is a public instance method that is defined in the ruby library especially for the Hash class. This method works in a way that invokes the block at least once for every individual key present in the hash object. The key-value pairs present in the hash object are passed as parameters. If you are not providing any block then you should expect an enumerator as the returned value from the each_pair method.
此方法是在ruby庫中定義的公共實例方法,尤其是針對Hash類。 此方法的工作方式是,針對哈希對象中存在的每個單個鍵至少調用一次該塊。 哈希對象中存在的鍵值對作為參數傳遞。 如果不提供任何塊,則應期望枚舉數作為each_pair方法的返回值。
Syntax:
句法:
Hash_object.each_pair{|key,value| block}
Argument(s) required:
所需參數:
This method does not accept any arguments. However, you can pass a block along with this method.
此方法不接受任何參數。 但是,您可以通過此方法傳遞一個塊。
Example 1:
范例1:
=begin
Ruby program to demonstrate each_pair method
=end
hsh={"name"=>"Zorawar","class"=>"ukg","school"=>"AASSC","place"=>"Haridwar"}
puts "Hash each_pair implementation"
str = hsh.each_pair{|key,value| puts "#{key} is #{value}"}
puts str
Output
輸出量
Hash each_pair implementation
name is Zorawar
class is ukg
school is AASSC
place is Haridwar
{"name"=>"Zorawar", "class"=>"ukg", "school"=>"AASSC", "place"=>"Haridwar"}
Explanation:
說明:
In the above code, you may observe that we are printing every key-value pair from the hash object with the help of the Hash.each_pair method. The method is invoking a block, which is taking the key value as the argument from the hash object. This method is traversing through the hash object, processing them and giving us the desired output or you can say that letting us know about the value stored in a particular key.
在上面的代碼中,您可能會看到,借助于Hash.each_pair方法 ,我們正在從哈希對象中打印每個鍵值對。 該方法正在調用一個塊,該塊將鍵值作為哈希對象的參數。 該方法遍歷哈希對象,對其進行處理并為我們提供所需的輸出,或者您可以說讓我們知道存儲在特定鍵中的值。
Example 2:
范例2:
=begin
Ruby program to demonstrate each_pair method
=end
hsh={"name"=>"Zorawar","class"=>"ukg","school"=>"AASSC","place"=>"Haridwar"}
puts "Hash each_pair implementation"
str = hsh.each_pair
puts str
Output
輸出量
Hash each_pair implementation
#<Enumerator:0x0000560701eb6820>
Explanation:
說明:
In the above code, you can observe that when we are invoking the method without the block then we are getting an enumerator returned from the method.
在上面的代碼中,您可以觀察到,當我們在不使用該塊的情況下調用該方法時,就會得到該方法返回的枚舉數。
翻譯自: https://www.includehelp.com/ruby/hash-each_pair-method-with-example.aspx
as_hash ruby