Skip to content

Instantly share code, notes, and snippets.

@ruevaughn
Created July 13, 2018 23:27
Show Gist options
  • Save ruevaughn/6ecd9c30eb113c733a7e9c3d14fb2180 to your computer and use it in GitHub Desktop.
Save ruevaughn/6ecd9c30eb113c733a7e9c3d14fb2180 to your computer and use it in GitHub Desktop.
As per our discussion at Verisys - Passing multiple arguments using a hash rather than listing them all out,
# Coming soon to a ruby script near you!
#!/usr/bin/env ruby
def get_word_count(string, n, opts={})
if string
puts "string received: #{string}"
end
if n
puts "n param received: #{n}"
end
if opts
pp "opts params that were received: #{opts}"
end
if opts[:top_word_count]
puts "opts[:top_word_count] is #{opts[:top_word_count]}"
end
end
get_word_count("This is a string that will be parse", 5, top_word_count: 5)
# Here is a link to a stack overflow method that I was attempting to use since I am not familiar with Keyword Arguments
# (kwargs). I actually almost have my personal website (https://www.chasejensen.com - not up yet) done and and going to
# be blogging actively. I think going to this in depth is going to be one of my first blog posts. For now, this stack
# overflow answer shows what I was initially reaching for when asked about passing multiple args properl
# https://stackoverflow.com/a/1935679
# And here is the Keyword Arguments (kwargs) you were mentioning! Sweet!
# # These are two great posts about this topic and both define kwargs in depth, I am going to be exploring this further!
# https://www.justinweiss.com/articles/fun-with-keyword-arguments/
# https://robots.thoughtbot.com/ruby-2-keyword-arguments
# # #
# Demonstration of using default hash value as last argument
def get_word_count(string, n, opts={})
if string
puts "string received: #{string}"
end
if n
puts "n param received: #{n}"
end
if opts
pp "opts params that were received: #{opts}"
end
if opts[:top_word_count]
puts "opts[:top_word_count] is #{opts[:top_word_count]}"
end
end
get_word_count("This is a string that will be parse", 5, top_word_count: 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment