0

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

this totally works but I was hoping to have an array object that I could further manipulate when expanding my method to include more features. Sorry I was not more precise in my question.
@SinGar you can expand your method without creating additional array, just create a variable (chars = word.split('')) or call other method on array (word.split('').manipulation).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.