boddhisattva
boddhisattva

Reputation: 7380

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?

Upvotes: 1

Views: 109

Answers (2)

Uri Agassi
Uri Agassi

Reputation: 37409

Although %W does interpolation (%w does not), it does not behave like a literal string with split. You can see an example in this blog post:

And I thought I was also aware of %W - which obviously would work just like %w except evaluating code inside. Except that's not what it does! %W[foo #{bar}] is not "foo #{bar}".split - it's ["foo", "#{bar}"]! And using a real parser of course, so you can use as many spaces inside that code block as you want.

system *%W[mongod --shardsvr --port #{port} --fork --dbpath #{data_dir}
--logappend --logpath #{logpath} --directoryperdb]

So in your case:

a = 'hi how are you'
%W(#{a})
# => ["hi how are you"]

So your count will still be 1.

The proper way to get 4 is to use split...

Upvotes: 0

Ankush Kataria
Ankush Kataria

Reputation: 323

You can use String#split.

For Example:

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

Upvotes: 2

Related Questions