Reputation: 75
Struggling to understand how an object can be created this way. What is happening behind the scenes here when constructing this object ?
class UserPreview < Struct.new(:gid, :email, :name)
end
u = UserPreview.new(1, '[email protected]', 'Hans Peter')
=> #<struct UserPreview gid=1, email="[email protected]", name="Hans Peter">
Upvotes: 3
Views: 110
Reputation: 26473
I think there are three things to discuss in your code:
# 1
Struct.new(:gid, :email, :name)
# 2
class UserPreview < OtherClass
end
# 3
u = UserPreview.new(1, '[email protected]', 'Hans Peter')
Starting with # 2:
UserPreview
is created as a standard sub-class from OtherClass
(in this case the result of the Struct.new
call). We see the sub-class is not adding any new methods or attributes so it is essentially the same class as OtherClass
with a different name. In Ruby you could simplify this as:
UserPreview = OtherClass
Because classes are just objects (of class Class).
Let's look at # 1:
What happens here is that we construct a new Struct instance with the given parameters. Under hood Struct
is manually implemented in Ruby using C. You can look at the code on Github. I think nothing particular surprising happens. The given symbols are used to create a new class (either anonymously or named) and set the members provided (see here)
Last let's look at # 3:
# 3
u = UserPreview.new(1, '[email protected]', 'Hans Peter')
In this case the C function rb_struct_initialize_m
is called. Since you provided just a list of arguments the code just walks the member fields and set each one in turn:
for (long i=0; i<argc; i++) {
RSTRUCT_SET(self, i, argv[i]);
Upvotes: 1