Created
March 30, 2012 19:50
-
-
Save mkoby/2254435 to your computer and use it in GitHub Desktop.
Intro to Ruby - 05 - Methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## Basic Method | |
| def say_hello | |
| puts “Hello” | |
| end | |
| hello # => Hello | |
| ## Method with an argument | |
| def say_hello_to(name) | |
| puts “Hello, #{name}” | |
| end | |
| say_hello_to("Michael") # => Hello, Michael | |
| ## Method with an argument with a default value | |
| def hello(name = nil) | |
| puts “Hello#{(‘,’ + name) if name}” | |
| end | |
| hello # => Hello | |
| hello("Michael") # => Hello, Michael | |
| ## Method that explicitly returns a value | |
| def hello(name = “”) | |
| s = “Hello” | |
| s += “, #{name}” unless name.empty? | |
| return s | |
| end | |
| hello # => "Hello" | |
| hello("Michael") # => "Hello, Michael" | |
| ## Because this method returns a string, we can use | |
| ## the method as the input to the PUTS method, to | |
| ## print the result of the method to the screen. | |
| puts hello("Michael") # => Hello, Michael | |
| ## Doing the above is the same as doing | |
| puts "Hello, Michael" | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ## Method takes a number, checks to see if | |
| ## it's divisible by 2, returns true if it | |
| ## is and returns false if it is not | |
| def is_divisible_by_2(number) | |
| if( number % 2 == 0) | |
| return true | |
| else | |
| return false | |
| end | |
| is_divisible_by_2(4) # => true | |
| is_divisible_by_2(5) # => false | |
| ## Method takes a number and returns the square | |
| ## This method doesn't use the RETURN keyword. | |
| ## In Ruby, the last line of a method is the | |
| ## returned value. | |
| def square(number) | |
| number * number | |
| end | |
| square(8) # => 64 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment