Upcase array

  • Thread starter Fredrik Jagenheim
  • Start date
F

Fredrik Jagenheim

Given this array:
foo = %w { FOO BAR baz biz }

How do I make all the entries uppercase in a short and readable way?

The (to me) obvious solution won't work:
foo.map! { |x| x.upcase! }
as upcase returns nil if it doesn't have anything to upcase...

//F
 
T

Thomas Leitner

On Wed, 6 Oct 2004 17:41:50 +0900

| Given this array:
| foo = %w { FOO BAR baz biz }
|
| How do I make all the entries uppercase in a short and readable way?
|
| The (to me) obvious solution won't work:
| foo.map! { |x| x.upcase! }
| as upcase returns nil if it doesn't have anything to upcase...
|
| //F
|
|

Do not use x.upcase! but x.upcase (without the exclamation mark):

irb(main):005:0> foo = %w{ FOO BAR baz biz }
=> ["FOO", "BAR", "baz", "biz"]
irb(main):006:0> foo.map! { |x| x.upcase }
=> ["FOO", "BAR", "BAZ", "BIZ"]

*hth*,
Thomas
 
R

Robert Klemme

Thomas Leitner said:
On Wed, 6 Oct 2004 17:41:50 +0900

| Given this array:
| foo = %w { FOO BAR baz biz }
|
| How do I make all the entries uppercase in a short and readable way?
|
| The (to me) obvious solution won't work:
| foo.map! { |x| x.upcase! }
| as upcase returns nil if it doesn't have anything to upcase...
|
| //F
|
|

Do not use x.upcase! but x.upcase (without the exclamation mark):

irb(main):005:0> foo = %w{ FOO BAR baz biz }
=> ["FOO", "BAR", "baz", "biz"]
irb(main):006:0> foo.map! { |x| x.upcase }
=> ["FOO", "BAR", "BAZ", "BIZ"]

Even more efficient is the usage of #each and #upcase!
foo = %w{ FOO BAR baz biz } => ["FOO", "BAR", "baz", "biz"]
foo.each {|s| s.upcase!} => ["FOO", "BAR", "BAZ", "BIZ"]

Here, no new instances are created.

Regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top