delete char

P

Pen Ttt

i want to make 'gkhj*&()' into 'gkhj',here is my code
item='gkhj*&()'
item=item.map{|echar|
if /[a-z]/=~ echar then
echar=echar
else
echar=''
end}
puts item
why i can't get what i want?
Any advice appriciated.
 
A

Ammar Ali

i want to make 'gkhj*&()' into 'gkhj',here is my code
=C2=A0item=3D'gkhj*&()'
=C2=A0item=3Ditem.map{|echar|
=C2=A0if /[a-z]/=3D~ echar then
=C2=A0 =C2=A0echar=3Dechar
=C2=A0else
=C2=A0 =C2=A0echar=3D''
=C2=A0end}
=C2=A0puts item
why i can't get what i want?
Any advice appriciated.

Much easier to use gsub with a negative character set for this:

puts item.gsub(/[^a-z]+/, '')

HTH,
Ammar
 
P

Pen Ttt

pt@pt-laptop:~$ irb
irb(main):001:0> 'gkhj*&()'[0]
=> 103
irb(main):002:0>

can i get 'gkhj*&()'[0]=>g??
 
H

Harry Kakueki

it is ok,but i want to know =A0why my code can't run?

I think you should take the advice of someone who shows you a Ruby way, but=
....

I looked at your code and modified it a little.
It seems to work but I'm tired so this is all I can offer now.

item=3D'gkhj*&()'
#item =3D '((c)?'
item=3Ditem.split(//).map{|echar|
if /[a-z]/=3D~ echar then
echar=3Dechar
else
echar=3D''
end}
p item*""

I would not do it this way but you wanted to know why your code did not wor=
k.



Harry
 
H

Harry Kakueki

pt@pt-laptop:~$ irb
irb(main):001:0> =A0'gkhj*&()'[0]
=3D> 103
irb(main):002:0>

can i get =A0'gkhj*&()'[0]=3D>g??

p 'gkhj*&()'[0] #Ruby 1.9
p 'gkhj*&()'.split(//)[0] #Ruby 1.8 ??


Harry
 
F

F. Senault

Le 29 août 2010 à 14:56, Pen Ttt a écrit :
pt@pt-laptop:~$ irb
irb(main):001:0> 'gkhj*&()'[0]
=> 103
irb(main):002:0>

can i get 'gkhj*&()'[0]=>g??

Not on every ruby version out there. You'd be better using this :
'gkhj*&()'[0, 1] => "g"
'gkhj*&()'[0..0]
=> "g"

(First is start index, count, the other is start index..end index ; both
work on rubies 1.8 and 1.9 at least.)

Fred
 

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,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top