Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The Ruby Workshop

You're reading from   The Ruby Workshop Develop powerful applications by writing clean, expressive code with Ruby and Ruby on Rails

Arrow left icon
Product type Paperback
Published in Oct 2019
Publisher Packt
ISBN-13 9781838642365
Length 544 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (4):
Arrow left icon
Dániel Szabó Dániel Szabó
Author Profile Icon Dániel Szabó
Dániel Szabó
Akshat Paul Akshat Paul
Author Profile Icon Akshat Paul
Akshat Paul
Peter Philips Peter Philips
Author Profile Icon Peter Philips
Peter Philips
Cheyne Wallace Cheyne Wallace
Author Profile Icon Cheyne Wallace
Cheyne Wallace
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Writing and Running Ruby Programs FREE CHAPTER 2. Ruby Data Types and Operations 3. Program Flow Ruby Methods 5. Object-Oriented programming with Ruby 6. Modules and Mixins 7. Introduction to Ruby Gems 8. Debugging with Ruby 9. Ruby Beyond the Basics l 10. Ruby Beyond the Basics ll 11. Introduction to Ruby on Rails l 12. Introduction to Ruby on Rails ll Appendix

9. Ruby Beyond the Basics I

Activity 9.01: Invoice Generator

Solution

  1. Create a new Ruby file.
  2. Define the invoice_generator method and the p1 and p2 variables to be used in the program using &block and block_given?. We call the invoice_generator method and pass the product prices along with a block of code:
    def invoice_generator(p1,p2, &block)
        yield calc_discount(p1,p2) if block_given?
    end

    The invoice_generator method has a yield keyword, which will only execute the block of code and pass the product prices if the first block of code is passed.

    First, calc_discount is called and then a block code is executed, which, in turn, passes the customer details to the details method.

  3. Next, we will define the discount calculator method, calc_discount, which will calculate the discount on the products, add it to the product, and print the final price of the product. calc_discount is the method where we calculate the sum of the product prices and...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image