daily pastebin goal
10%
SHARE
TWEET

Untitled

a guest Aug 14th, 2018 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ### Method argument syntax
  2. Methods can be written with or without parenthesis. Methods can be called with arguments passed in with or without parenthesis, regardless of how the method was defined.
  3.  
  4. #### Method syntax with parenthesis
  5.  
  6. ```ruby
  7. def full_name(first_name, last_name)
  8.   first_name + " " + last_name
  9. end
  10. ```
  11.  
  12. Calling method with parenthesis:
  13. ```
  14. $ puts full_name("Johnny", "Apples")
  15. Johnny Apples
  16. => nil
  17. ```
  18.  
  19. #### Method syntax without parenthesis
  20.  
  21. ```ruby
  22. def full_name first_name, last_name
  23.   first_name + " " + last_name
  24. end
  25. ```
  26.  
  27. Calling method without parenthesis:
  28. ```
  29. $ puts full_name "Johnny", "Apples"
  30. Johnny Apples
  31. => nil
  32. ```
  33.  
  34. ### Method syntax with named arguments
  35.  
  36. Using named arguments allow you to pass arguments to a method in any order without effecting the result of the method, and it's much more explicit. Can also be used with or without parenthesis.
  37.  
  38. ```ruby
  39. def print_address city:, state:, zip:
  40.   puts city
  41.   puts state
  42.   puts zip
  43. end
  44. ```
  45.  
  46. Calling `print_address` in defined order:
  47. ```
  48. $ print_address city: "New York", state: "NY", zip: 10014
  49. New York
  50. NY
  51. 10014
  52. => nil
  53. ```
  54.  
  55. Calling `print_address` in alternate order:
  56. ```
  57. $ print_address  zip: 10014, city: "New York",  state: "NY"
  58. New York
  59. NY
  60. 10014
  61. => nil
  62. ```
  63.  
  64. ### Method syntax with named arguments and default values
  65. Default values can be used to set a default parameter which can be overridden on method call.
  66.  
  67. ```ruby
  68. def book title:, language: "EN"
  69.   puts title
  70.   puts language
  71. end
  72. ```
  73.  
  74. Calling `book` with a default value:
  75. ```
  76. $ book title: "The Mist", language: "EN"
  77. The Mist
  78. EN
  79. => nil
  80. ```
  81.  
  82. Calling `book` without defining a value:
  83. ```
  84. $ book title: "The Mist"
  85. The Mist
  86. EN
  87. => nil
  88. ```
  89.  
  90. Calling `book` and overriding the default value:
  91. ```
  92. $ book title: "The Idiot", language: "RU"
  93. The Idiot
  94. RU
  95. => nil
  96. ```
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top