Space in the Ruby Array by %W

Space in the ruby array by %w

Escape it:

%w(a b\ c) # => ["a", "b c"]

Word array with whitespace

You can escape space characters

a = %w[ faq contact about\ us legal bug\ reports ]
a # => ["faq", "contact", "about us", "legal", "bug reports"]

But I'd still consider using "full" array literals. They are less confusing in this case.

including spaces while using %w

a = ["xyz"].split("").join(" ")

or

a = ["x","y","z"].join(" ")

or

a = %w(x y z).join(" ")

What does %w(array) mean?

%w(foo bar) is a shortcut for ["foo", "bar"]. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in zenspider's quickref.

Im try to isolate the white space in ruby sentences

You're getting the "wrong number of arguments" error here:

words[x].include? != " "

You can quickly fix this by replacinng it with:

!words[x] == " "

A better way to do the whole thing would be:

words.gsub(" ", "0").chars

Ruby (Rails): remove whitespace from each array item

This is what collect is for.

The following handles nil elements by leaving them alone:

yourArray.collect{ |e| e ? e.strip : e }

If there are no nil elements, you may use:

yourArray.collect(&:strip)

...which is short for:

yourArray.collect { |e| e.strip }

strip! behaves similarly, but it converts already "stripped" strings to nil:

[' a', ' b ', 'c ', 'd'].collect(&:strip!)
=> ["a", "b", "c", nil]

https://ruby-doc.org/core/Array.html#method-i-collect

https://ruby-doc.org/core/String.html#method-i-strip

Using %i and %I symbol array literal

I'm having trouble finding what the %i does in relation to a symbol array.

It is an array literal for an array of symbols. It does the same thing in relation to symbol arrays as ' does to strings.



Related Topics



Leave a reply



Submit