1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Merge pull request #21782 from ronakjangir47/transform_values_docs

Updated docs for transform_keys & transform_values
This commit is contained in:
Rafael Mendonça França 2015-09-28 13:19:00 -03:00
commit 9254d7eb11
2 changed files with 17 additions and 8 deletions

View file

@ -1,10 +1,14 @@
class Hash class Hash
# Returns a new hash with all keys converted using the block operation. # Returns a new hash with all keys converted using the +block+ operation.
# #
# hash = { name: 'Rob', age: '28' } # hash = { name: 'Rob', age: '28' }
# #
# hash.transform_keys{ |key| key.to_s.upcase } # hash.transform_keys { |key| key.to_s.upcase } # => {"NAME"=>"Rob", "AGE"=>"28"}
# # => {"NAME"=>"Rob", "AGE"=>"28"} #
# If you do not provide a +block+, it will return an Enumerator
# for chaining with other methods:
#
# hash.transform_keys.with_index { |k, i| [k, i].join } # => {"name0"=>"Rob", "age1"=>"28"}
def transform_keys def transform_keys
return enum_for(:transform_keys) unless block_given? return enum_for(:transform_keys) unless block_given?
result = self.class.new result = self.class.new
@ -14,8 +18,8 @@ class Hash
result result
end end
# Destructively converts all keys using the block operations. # Destructively converts all keys using the +block+ operations.
# Same as transform_keys but modifies +self+. # Same as +transform_keys+ but modifies +self+.
def transform_keys! def transform_keys!
return enum_for(:transform_keys!) unless block_given? return enum_for(:transform_keys!) unless block_given?
keys.each do |key| keys.each do |key|

View file

@ -2,8 +2,12 @@ class Hash
# Returns a new hash with the results of running +block+ once for every value. # Returns a new hash with the results of running +block+ once for every value.
# The keys are unchanged. # The keys are unchanged.
# #
# { a: 1, b: 2, c: 3 }.transform_values { |x| x * 2 } # { a: 1, b: 2, c: 3 }.transform_values { |x| x * 2 } # => { a: 2, b: 4, c: 6 }
# # => { a: 2, b: 4, c: 6 } #
# If you do not provide a +block+, it will return an Enumerator
# for chaining with other methods:
#
# { a: 1, b: 2 }.transform_values.with_index { |v, i| [v, i].join.to_i } # => { a: 10, b: 21 }
def transform_values def transform_values
return enum_for(:transform_values) unless block_given? return enum_for(:transform_values) unless block_given?
return {} if empty? return {} if empty?
@ -14,7 +18,8 @@ class Hash
result result
end end
# Destructive +transform_values+ # Destructively converts all values using the +block+ operations.
# Same as +transform_values+ but modifies +self+.
def transform_values! def transform_values!
return enum_for(:transform_values!) unless block_given? return enum_for(:transform_values!) unless block_given?
each do |key, value| each do |key, value|