Advertisement
karlakmkj

Splat arguments & Blocks

Sep 2nd, 2021
489
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.93 KB | None | 0 0
  1. # Splat arguments - can receive more than 1 arguments
  2.  
  3. def what_up(greeting, *friends)
  4.   friends.each { |friend| puts "#{greeting}, #{friend}!" }
  5. end
  6.  
  7. what_up("What up", "Ian", "Zoe", "Zenas", "Eleanor")
  8.  
  9. # Blocks can be defined with either the keywords do and end or with curly braces ({}).
  10. 1.times do
  11.   puts "I'm a code block!"
  12. end
  13.  
  14. 1.times { puts "As am I!" }
  15.  
  16. =begin
  17. However, the block that we define (following .each) will only be called once, and in the context of the array that we are iterating over.
  18. Hence it's better to use method than blocks if there is a need of reuse.
  19. =end
  20.  
  21. # method that capitalizes a word
  22. def capitalize(string)
  23.   puts "#{string[0].upcase}#{string[1..-1]}"
  24. end
  25.  
  26. capitalize("ryan") # prints "Ryan"
  27. capitalize("jane") # prints "Jane"
  28.  
  29. # block that capitalizes each string in the array
  30. ["ryan", "jane"].each {|string| puts "#{string[0].upcase}#{string[1..-1]}"} # prints "Ryan", then "Jane"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement