string to substring??

  • Thread starter Pat Kiatchaipipat
  • Start date
P

Pat Kiatchaipipat

I have one string name

message = "5x-2=18"

and I want to create substring or array by this

mesArray[0] = 5
mesArray[1] = x
mesArray[2] = -
...

this has function?
how can I make it?
 
I

Ilan Berci

Pat said:
I have one string name

message = "5x-2=18"

and I want to create substring or array by this

mesArray[0] = 5
mesArray[1] = x
mesArray[2] = -
...

this has function?
how can I make it?

irb(main):001:0> mesArray = "5x-2=18".split ""
=> ["5", "x", "-", "2", "=", "1", "8"]
 
R

Robert Klemme

2007/12/3 said:
I have one string name

message = "5x-2=18"

and I want to create substring or array by this

mesArray[0] = 5
mesArray[1] = x
mesArray[2] = -
...

this has function?
how can I make it?

You have that already in your String:

irb(main):001:0> message = "5x-2=18"
=> "5x-2=18"
irb(main):002:0> message[0].chr
=> "5"
irb(main):003:0> message[1].chr
=> "x"
irb(main):004:0> message[2].chr
=> "-"

I am suspecting though that what you really want is a parser for
expressions. A simplistic version could look like this:

irb(main):005:0> message.scan %r{\d+|\w+|[-+=]}
=> ["5", "x", "-", "2", "=", "18"]

If you want to properly process expressions with brackets etc. you
need a more complex solution.

Kind 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,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top