0

I have a piece of Ruby code I don't understand:

Line = Struct.new(name, "example") // what happens here? def foo(lines) lines.map { |z| Line.new(name, z[:specific]) // equal to 'Struct.new'? } end 

Does it mean that Line is an alias for Struct now? Or what else happens here?

1

3 Answers 3

1

Line is new class, one returned by Struct.new. Struct is a helper class that allows you to easily create classes with accessor methods to fields with names given as its constructor arguments. It might be confusing at first, but in Ruby classes are just another type of objects, and so they can be created by methods.

You can get reference on how Struct works here: http://ruby-doc.org/core-2.2.2/Struct.html

Sign up to request clarification or add additional context in comments.

Comments

1

The Struct is just shorthand notation for this class:

class Line def initialize(example, name) @example = example @name = name end def name=(name) @name = name end def name @name end def example=(example) @example = example end def example @example end end 

When you see Line.new, just think of it as an instance of the Line class. The Sruct is just a quicker way of creating the Line class.

Comments

0

Does it mean that Line is an alias for Struct now?

No. That would be something like

Line = Struct 
Line = Struct.new(name, "example") // what happens here? 
  1. Dereference the constant Struct
  2. send the message name without arguments to self
  3. send the message new with two arguments to the object returned in 1, the first argument is the object returned in 2., the second argument is the literal string "example"
  4. assign the object returned in 3. to the constant Line
Line.new(name, z[:specific]) // equal to 'Struct.new'? 

No, that's not how assignments work in Ruby. In Ruby, you don't assign an expression to a variable, the expression gets evaluated first, and then the result of that evaluation gets assigned to the variable once.

I.e. if you do something like

foo = gets 

gets does not get called over and over again, every time you dereference foo, it gets called once when you assign to foo and then foo contains a reference to the object returned by gets.

Besides, even if it worked like you seem to think it does, then it still wouldn't be equal to Struct.new but rather to Struct.new(name, "example").new, because that's the expression that was on the right-hand side of the assignment to Line (but, like I said, it doesn't work like that).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.