Convert MatchData to Integer

Discussion in 'Ruby' started by qoexcel, Jun 2, 2014.

  1. qoexcel

    qoexcel Guest

    Hi Everyone,i want to get integer from string, something like this:

    <Loading DOM finished: 41 ms>

    using command /\d+/.match(self.loadDOMstat)

    , but actually i don't have integer, i have MatchData .
    How can i convert MatchData to integer in Ruby?Moreover you can give me a hint, how to get number from this string..
    Thank you in advance!!!
    qoexcel, Jun 2, 2014
    1. Advertisements

  2. Generally you use method Integer() to convert String into an int:

    irb(main):001:0> s = "123"
    => "123"
    irb(main):002:0> n = Integer(s)
    => 123
    irb(main):003:0> n.class
    => Fixnum

    In your case you can do this:

    irb(main):004:0> s = '<Loading DOM finished: 41 ms>'
    => "<Loading DOM finished: 41 ms>"
    irb(main):005:0> n = s[/<Loading DOM finished: (\d+) ms/, 1]
    => "41"
    irb(main):006:0> n = Integer(n)
    => 41


    Robert Klemme, Jun 2, 2014
    1. Advertisements

  3. qoexcel

    qoexcel Guest

    вторник, 3 Ð¸ÑŽÐ½Ñ 2014 г., 0:11:38 UTC+4 пользователь Robert Klemme напиÑал:
    Thank you very much, Robert!! Yes, now i have number (fixnum)
    I have also problem, i try to add this value to array element :
    convert_loadDOM = self.loadDOMstat
    n1 = convert_loadDOM[/Loading DOM finished: (\d+) ms/, 1]
    files_load_DOM= files_load_DOM + Integer(n1)

    and i have error:
    undefined method `+' for nil:NilClass (NoMethodError)
    qoexcel, Jun 3, 2014
  4. Good evening

    On Tue, 3 Jun 2014 03:22:25 -0700 (PDT),
    Where in your code did you initialize 'files_load_DOM' to an
    Array-object or other container-type with a '[]' method and add a first
    element to it?

    Not here!
    At least, that is, what the message points at.


    Michael Uplawski, Jun 3, 2014

  5. files_load_DOM ist most likely nil - either because i points past the
    last index of the Array or you never put a value there.

    Kind regards

    Robert Klemme, Jun 3, 2014
  6. qoexcel


    Dec 21, 2012
    Likes Received:
    files_load_DOM = [] if files_load_DOM==nil
    files_load_DOM << Integer(n1) # or files_load_DOM = files_load_DOM + [ Integer(n1) ]
    sevk, Sep 1, 2014
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.