2017-10-10 30 views
0

有一個助手#number_to_human來打印大數字,但有沒有一個相反的幫助來解析大數字,類似於strtotime()是否存在解析人數的寶石?

No specific search resultsRuby Toolbox已經死了。

獎勵將接受一個區域設置,以處理,.

我想解析之類的東西

  • $1米
  • $ 15萬
  • $ 999k
  • $ 111中號
  • 1,234,567.89
  • €987.654,00
  • 11億美元
+0

看看這個https://github.com/cyzanfar/Academy-Award-Best-Picture-scraper/blob/master/lib/academy_award_best_picture_scraper.rb#L37 可能會幫助您使用您解決問題正則表達式 – Cyzanfar

回答

2

我找到了一些東西並進行了定製。

def human_to_number(human) 
    return human unless human.is_a? String 
    return human if human.blank? # leave '' as is 
    human.downcase! 
    if human.index('k') || human.index('thousand') 
     multiplier = 1000 
    elsif human.index('m') 
     multiplier = 1_000_000 
    elsif human.index('b') 
     multiplier = 1_000_000_000 
    elsif human.index('t') 
     multiplier = 1_000_000_000_000 
    else 
     multiplier = 1 
    end 
    number = human.gsub(/[^0-9\.]/,'').to_f 
    number = number * multiplier 
    end 



irb(main):003:0> d.human_to_number '$1.2 million' 
=> 1200000.0 
irb(main):004:0> d.human_to_number '$1.2 billion' 
=> 1200000000.0 
irb(main):005:0> d.human_to_number '$1.2k' 
=> 1200.0 
irb(main):006:0> d.human_to_number '1.2k' 
=> 1200.0 
irb(main):007:0> d.human_to_number '555.66k' 
=> 555660.0