Search code examples
rubyarraysstringwords

Using %w with runtime input


I'm trying to use %w with a string input at run time. When I run this program:

a = gets.chomp
puts %w(a).count

with the input 'hi how are you', the output is 1. %w(a).count doesn't replace a with the input string.

While %w(hi how are you).length is 4, %w(a) treats a as a single entity and its count value is 1.

How can I print the length 4 or any number for a string that is input at run time?


Solution

  • You can use String#split.

    For Example:

    a = "hi how are you"
    a.split(" ").size