First and last element ruby has [" and "]

Viewed 69

I'm trying to get a array from a string passed as parameters to match a dictionary after.

My code:

def substrings(*args, dictionary)
  words = args.to_s.split(" ")

  puts words[0]
  puts words[1]
  puts words[2]

end


substrings("below as above", dictionary)

The result is

["below
as
above"]

Why the first and last elements has this [" and "]??

Hope I was clear.

1 Answers

* in *args means that you collect arbitrary amount of arguments in array args, so "below as above" transforms into ["below as above"] array, and .to_s converts it into string '["below as above]', that's why you receive this strange result.

If you want only one (first) string argument, you may change code as below:

def substrings(str, dictionary)
  words = str.split

  puts words[0]
  puts words[1]
  puts words[2]

end


substrings("below as above", dictionary)
# output:
# below
# as
# above

Or, if you really want to pass any amount of strings:

def substrings(*args, dictionary)
  words = args.map(&:split).flatten

  words.each { |word| puts word }
end


substrings("below as above", "foo is not a bar", dictionary)
# output:
# below
# as
# above
# foo
# is
# not
# a
# bar
Related