What are the differences between Ruby's Double Splat and Ruby's other features?

Asked 2 years ago, Updated 2 years ago, 34 views

Drat!-Ruby has a Double Splat-Firmafon Developers Blog

I saw .

deff(**options)
  options#=>{:hoge=>"AAA",:foo=>"BBB"}
end

foge: "AAA", foo: "BBB"

and

deff(options={})
  options#=>{:hoge=>"AAA",:foo=>"BBB"}
end

foge: "AAA", foo: "BBB"

What is the difference between ?

deff(options={})
  options#=>nil
end

finil

(No problem)

error

deff(**options)
  options
end

finil

`f': wrong number of arguments (1 for 0) (ArgumentError)

I don't know the criteria, but do you mean that the number of errors is increasing depending on the type given in the actual argument?

 options={a:'b'}
hoge={c:'d',**options}
hoge#=>{:c=>"d",:a=>"b"}

fuga={c:'d'}.merge(options)
pfuga#=>{:c=>"d",:a=>"b"}

Is it the same?

ruby

2022-09-30 18:31

1 Answers

Q2. What is the difference between ** and the merge method?

The hash literal doesn't tell the difference, so I'll make it a variable.

For {**Hash,**Hash},

irb>h1={a:'b'}
=>{:a=>"b"}
irb>h2 = {c:'d'}
=>{:c=>"d"}
irb>h12 = {**h1,**h2}
=>{:a=>"b",:c=>"d"}
irb>h1
=>{:a=>"b",:c=>"d"}
irb>h2
=>{:c=>"d"}

for the merge method

irb>h1={a:'b'}
=>{:a=>"b"}
irb>h2 = {c:'d'}
=>{:c=>"d"}
irb>h12 = h1.merge(h2)
=>{:a=>"b",:c=>"d"}
irb>h1
=>{:a=>"b"}
irb>h2
=>{:c=>"d"}

For {**Hash,**Hash}, h1 has been rewritten.This is the same as Hash.merge!().

irb>h12=h1.merge!(h2)
=>{:a=>"b",:c=>"d"}
irb>h1
=>{:a=>"b",:c=>"d"}
irb>h2
=>{:c=>"d"}

The source code is as follows, and in the case of Hash.merge(), you will find that a copy has been passed.

ruby-2.6/hash.c

/*
 *  call-seq:
 *     hsh.merge(other_hash)
            :
*/
static VALUE
rb_hash_merge (VALUE hash1, VALUE hash2)
{
    return rb_hash_update(rb_obj_dup(hash1), hash2);
                          ^^^^^^^^^^^^^^^^^
}

/*
 *  call-seq:
 *     US>hsh.merge! (other_hash)
            :
 */
static VALUE
rb_hash_update (VALUE hash1, VALUE hash2)
{
    rb_hash_modify(hash1);
            :


2022-09-30 18:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.