String to substring?

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?

Pat K. wrote:

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”]

2007/12/3, Pat K. [email protected]:

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

thank you robert :smiley:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs