Forum: Ruby equivalent of perl qw operator

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Vlad C. (Guest)
on 2007-04-12 02:05
(Received via mailing list)
I have a feeling I've seen it in the pickaxe book but I can't seem to
find
it again.

Is there a way to write this differently?

array = [ 'element1', 'element2', ...]

In perl I could do

@array = qw( element1 element2 ...)

without the quotes.

thanks
vlad
Augie De Blieck Jr. (Guest)
on 2007-04-12 02:20
(Received via mailing list)
Page 15 of the Pick Axe book, as a matter of fact.  It's %w{ }

-Augie
Timothy H. (Guest)
on 2007-04-12 02:21
(Received via mailing list)
Vlad C. wrote:
> Is there a way to write this differently?
>
> array = [ 'element1', 'element2', ...
%w{element1 element2}
Mike M. (Guest)
on 2007-04-12 02:24
(Received via mailing list)
On 4/11/07, Vlad C. <removed_email_address@domain.invalid> wrote:
> @array = qw( element1 element2 ...)
>
> without the quotes.


irb(main):001:0> @array = %w{element1 element2}
=> ["element1", "element2"]

thanks
Chad P. (Guest)
on 2007-04-12 02:30
(Received via mailing list)
On Thu, Apr 12, 2007 at 07:19:28AM +0900, Augie De Blieck Jr. wrote:
> Page 15 of the Pick Axe book, as a matter of fact.  It's %w{ }

Also . . . if you want to get string interpolation as though you used
double quotes around your list elements, rather than single quotes, you
can capitalize the W in that.  In other words:

  irb(main):001:0> foo = 'one'
  => "one"
  irb(main):002:0> bar = %w{ #{foo} two }
  => ["\#{foo}", "two"]
  irb(main):003:0> bar = %W{ #{foo} two }
  => ["one", "two"]
Vlad C. (Guest)
on 2007-04-12 03:56
(Received via mailing list)
Awesome! Thanks to all.

vlad
Reuben G. (Guest)
on 2007-04-12 04:06
(Received via mailing list)
Vlad C. wrote:
>> array = [ 'element1', 'element2', ...]
>>
>> In perl I could do
>>
>> @array = qw( element1 element2 ...)
>>
>> without the quotes.
>>
>> thanks
>> vlad
>

Also note that you can use other delimiters besides { and }:
irb(main):002:0> %w| bob jack harry |
=> ["bob", "jack", "harry"]
irb(main):003:0> %w( bob jack harry )
=> ["bob", "jack", "harry"]
irb(main):005:0> %w[ bob jack harry ]
=> ["bob", "jack", "harry"]
irb(main):006:0> %w< bob jack harry >
=> ["bob", "jack", "harry"]
irb(main):007:0> %w@ bob jack harry @
=> ["bob", "jack", "harry"]
irb(main):010:0> %w! bob jack harry !
=> ["bob", "jack", "harry"]

The following don't work:

irb(main):004:0> %w) bob jack harry (
irb(main):005:0]

^C
irb(main):008:0> %www bob jack harry www
SyntaxError: compile error
(irb):8: unknown type of %string
%www bob jack harry www
    ^
         from (irb):8
This topic is locked and can not be replied to.