[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Upcase array

Fredrik Jagenheim

10/6/2004 8:42:00 AM

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


4 Answers

Thomas Leitner

10/6/2004 9:15:00 AM

0

On Wed, 6 Oct 2004 17:41:50 +0900
Fredrik Jagenheim <jagenheim@gmail.com> wrote:

| 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

Robert Klemme

10/6/2004 9:19:00 AM

0


"Thomas Leitner" <t_leitner@gmx.at> schrieb im Newsbeitrag
news:20041006111500.3dd9454c@localhost...
> On Wed, 6 Oct 2004 17:41:50 +0900
> Fredrik Jagenheim <jagenheim@gmail.com> wrote:
>
> | 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

Bill Atkins

10/6/2004 2:41:00 PM

0

Why does upcase! do this?

On Wed, 6 Oct 2004 17:41:50 +0900, Fredrik Jagenheim
<jagenheim@gmail.com> wrote:
> as upcase returns nil if it doesn't have anything to upcase...


Robert Klemme

10/6/2004 3:08:00 PM

0


"Bill Atkins" <batkins57@gmail.com> schrieb im Newsbeitrag
news:66b7e34b0410060741772b1a10@mail.gmail.com...
> Why does upcase! do this?

To give you a chance to determine whether the string has changed like in:

def treat(str)
if str.upcase!
puts "Ooops, it has changed!"
end
end

Kind regards

robert