Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

created train Struct #22

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

timsvoice
Copy link

I have a question:
I followed the recipe.rb pattern, but instead of placing an array (am I right in thinking the [ ] signify an array?), I wanted just a single passenger name. But puts "#{value}" output was blank.

This is the code I tried:

train = {}
train[:city] = "Johannesburg"
train[:engines] = 2
train[:cars] = 10
train[:caboose] = true

Passenger = Struct.new(:train, :name)

passenger = Passenger.new( {city: "New York", engines: 2, cars: 10, caboose: true}, "Timothy Voice")

puts "Train"
passenger.train.each do |key, value|
    puts "* #{key}: #{value}"
end

puts "\nPassenger"
passenger.name do |value|
    puts "#{value}"
end

@jwo
Copy link
Member

jwo commented May 13, 2014

passenger.name do |value|
    puts "#{value}"
end

The actual thing you're doing here is sending a "block" to passenger.name. For a block to be executed, and for the thing inside "do/end" to run, the method passenger.name must "yield" to it.

This is pretty close to what that passenger.name method looks like:

def name
  self.attributes["name"]
end

It would have to do something like this to do a block:

def name
  yield
  self.attributes["name"]
end

So, you could do this:

Passenger = Struct.new(:train, :name) do
  def name
    yield
    super
  end
end

But really, you should just:

puts "\nPassenger"
puts "#{passenger.name}"

@timsvoice
Copy link
Author

Excellent. That makes, sense.
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants