instance method
Data#with
(**untyped) -> self
with(**kwargs) → instance
struct.c
View on GitHub ↗
static VALUE
rb_data_with(int argc, const VALUE *argv, VALUE self)
{
VALUE kwargs;
rb_scan_args(argc, argv, "0:", &kwargs);
if (NIL_P(kwargs)) {
return self;
}
VALUE h = rb_struct_to_h(self);
rb_hash_update_by(h, kwargs, 0);
return rb_class_new_instance_kw(1, &h, rb_obj_class(self), TRUE);
}
Returns a shallow copy of self — the instance variables of self are copied, but not the objects they reference.
If the method is supplied any keyword arguments, the copy will be created with the respective field values updated to use the supplied keyword argument values. Note that it is an error to supply a keyword that the Data class does not have as a member.
Example
Point = Data.define(:x, :y) origin = Point.new(x: 0, y: 0) up = origin.with(x: 1) right = origin.with(y: 1) up_and_right = up.with(y: 1) p origin # #<data Point x=0, y=0> p up # #<data Point x=1, y=0> p right # #<data Point x=0, y=1> p up_and_right # #<data Point x=1, y=1> out = origin.with(z: 1) # ArgumentError: unknown keyword: :z some_point = origin.with(1, 2) # ArgumentError: expected keyword arguments, got positional arguments