SinGar SinGar - 6 months ago 7
Ruby Question

converting a string to an array and I keep getting an array with 1 object with the string crammed in that single index

I am new to ruby and trying to create a method that takes a string and returns an array with each letter as their own index in an array.

def validate_word(word)
w=[]
word.downcase!
w << word.split(//)
return w
end
validate_word("abcABC")

=> [["a", "b", "c", "a", "b", "c"]]


I would like it to return

=>["a", "b", "c", "a", "b", "c"]


Thank you for looking at my code.

Answer

In your code you do not need to create a new array, since String#split returns array which you want. Also, Ruby returns last string of a method by default, so you can write:

def validate_word(word)
  word.downcase! 
  word.split(//) # or you can chain methods: word.downcase.split('')
end
validate_word("abcABC")
=> ["a", "b", "c", "a", "b", "c"]

Note: do not use methods with exclamation mark (downcase!) except cases when you want modify source object. Use alternative methods(downcase) instead.

Comments