Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Hash#transform_values
() -> ::Enumerator[V, ::Hash[K, untyped]]
[A] () { (V) -> A } -> ::Hash[K, A]
hash.transform_values {|value| ... } → new_hash
hash.transform_values → new_enumerator
hash.c
View on GitHub ↗
static VALUE
rb_hash_transform_values(VALUE hash)
{
VALUE result;
RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
result = hash_dup_with_compare_by_id(hash);
SET_DEFAULT(result, Qnil);
if (!RHASH_EMPTY_P(hash)) {
rb_hash_stlike_foreach_with_replace(result, transform_values_foreach_func, transform_values_foreach_replace, result);
compact_after_delete(result);
}
return result;
}
Returns a new Hash object; each entry has:
-
A key from
self. -
A value provided by the block.
Transform values:
Example
h = {foo: 0, bar: 1, baz: 2} h1 = h.transform_values {|value| value * 100} h1 # => {:foo=>0, :bar=>100, :baz=>200}
Returns a new Enumerator if no block given:
Example
h = {foo: 0, bar: 1, baz: 2} e = h.transform_values # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_values> h1 = e.each { |value| value * 100} h1 # => {:foo=>0, :bar=>100, :baz=>200}
See also
#transform_values!
#transform_keys!
#transform_keys
#update
also in
4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0