1 / 5

Easy Ruby Methods for Learning & Fun Programming

Explore Ruby methods easily with examples like addem, block_sent, give_back. Learn how to use methods to build classes in Ruby effortlessly. Methods in Ruby can take a fixed or variable number of parameters and return the value of the last statement executed.

Download Presentation

Easy Ruby Methods for Learning & Fun Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Methods Learning Ruby - 7

  2. Ruby Methods are Easy! def addem ( first, second ) first + second end # of addem. addem( 23, 6 ) def addemall ( first, *rest ) rest.each { |r| first = first + r } first end # of addemall. addemall( 1, 2, 3, 4, 5, 6, 7 )

  3. Yield def block_sent? ( what ) if block_given? yield( what ) else what end # of if. end # of block_sent? block_sent?( 22 ) block_sent?( 22 ) { |num| num*num } block_sent?( 22 ) { |num| num+num }

  4. Fun with return def give_back ( a, *b ) return a end # of give_back. give_back( 10 ) give_back( 10, 11 ) def give_back2 ( a, *b ) return a, b.flatten end # of give_back2. give_back2( 10 ) give_back2( 10, 11 ) give_back2( 10, 11, 12, 13 ) first, rest = give_back2( 1, 2, 3, 4, 5 )

  5. More ... Ruby So Far • Methods can take no, a fixed number or a variable number of parameters as arguments • The value of the last statement executed is returned by the method (unless an explicit return is used) • Methods are what you use to build classes in Ruby

More Related