string to substring??

Discussion in 'Ruby' started by Pat Kiatchaipipat, Dec 3, 2007.

  1. 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?
    --
    Posted via http://www.ruby-forum.com/.
    Pat Kiatchaipipat, Dec 3, 2007
    #1
    1. Advertising

  2. Pat Kiatchaipipat

    Ilan Berci Guest

    Pat Kiatchaipipat 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"]
    --
    Posted via http://www.ruby-forum.com/.
    Ilan Berci, Dec 3, 2007
    #2
    1. Advertising

  3. 2007/12/3, 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?


    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

    --
    use.inject do |as, often| as.you_can - without end
    Robert Klemme, Dec 3, 2007
    #3
  4. Pat Kiatchaipipat, Dec 3, 2007
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. juli
    Replies:
    3
    Views:
    8,858
    Shiva
    Dec 6, 2004
  2. Badass Scotsman

    Finding a SubString within a String

    Badass Scotsman, Mar 31, 2006, in forum: ASP .Net
    Replies:
    2
    Views:
    6,122
    S. Justin Gengo
    Mar 31, 2006
  3. Michael Berg
    Replies:
    0
    Views:
    479
    Michael Berg
    May 30, 2004
  4. Replies:
    3
    Views:
    196
    Sherm Pendley
    Aug 3, 2005
  5. SM
    Replies:
    4
    Views:
    208
Loading...

Share This Page