Delete char

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.

On Sun, Aug 29, 2010 at 12:02 PM, Pen T. [email protected] wrote:

Any advice appriciated.
Much easier to use gsub with a negative character set for this:

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

HTH,
Ammar

it is ok,but i want to know why my code can’t run?

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

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

On Sun, Aug 29, 2010 at 9:45 PM, Pen T. [email protected] wrote:

it is ok,but i want to know why my code can’t run?

Posted via http://www.ruby-forum.com/.

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=‘gkhj*&()’
#item = ‘((c)?’
item=item.split(//).map{|echar|
if /[a-z]/=~ echar then
echar=echar
else
echar=‘’
end}
p item*“”

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

Harry

Le 29 août 2010 à 14:56, Pen T. 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

On Sun, Aug 29, 2010 at 9:56 PM, Pen T. [email protected] wrote:

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

Harry