diff --git a/README.md b/README.md index 94c8628..529b527 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1145 TILs and counting..._ +_1146 TILs and counting..._ --- @@ -889,6 +889,7 @@ _1145 TILs and counting..._ - [Create Thumbnail Image For A PDF](ruby/create-thumbnail-image-for-a-pdf.md) - [Defaulting To Frozen String Literals](ruby/defaulting-to-frozen-string-literals.md) - [Define A Custom RSpec Matcher](ruby/define-a-custom-rspec-matcher.md) +- [Define A Method On A Struct](ruby/define-a-method-on-a-struct.md) - [Destructuring Arrays In Blocks](ruby/destructuring-arrays-in-blocks.md) - [Disassemble Some Codes](ruby/disassemble-some-codes.md) - [Double Splat To Merge Hashes](ruby/double-splat-to-merge-hashes.md) diff --git a/ruby/define-a-method-on-a-struct.md b/ruby/define-a-method-on-a-struct.md new file mode 100644 index 0000000..644a85a --- /dev/null +++ b/ruby/define-a-method-on-a-struct.md @@ -0,0 +1,28 @@ +# Define A Method On A Struct + +When defining a Ruby `Struct`, you can optionally pass it a block that defines +any number of methods as instance methods on that `Struct`. They can reference +the attributes of the `Struct`. + +Here is an example of a person `Struct` with a `full_name` method that uses the +`first_name` and `last_name` attributes. + +```ruby +Person = Struct.new(:first_name, :last_name, :age) do + def full_name + "#{first_name} #{last_name}" + end +end +``` + +This `Struct` can be used like so: + +```ruby +> liz = Person.new("Liz", "Lemon", 39) +=> # +> liz.full_name +=> "Liz Lemon" +``` + +This is a great way to make a `Struct` just a bit more powerful without having +to convert it into a full-blown PORO (plain old Ruby object).