我喜欢HTML:
<div id="c_pcnb" style="height:11px;width:4px;visibility:hidden;position:absolute;">
我希望总结4px
和11px
,但我不知道如何。我只是得到这些值,但我没有使用组和两个值。我该怎么做?
@sizes = (/height:([\d]+)px;width:([\d]+)px;visibility:hidden;position:absolute;/.match body_text)
我必须加总高度+宽度。
当我尝试@sizes[1] + @sizes[2]
时,我会收到错误。我做错了什么?
答案 0 :(得分:3)
试试这个:
'<div id=\"c_pcnb\" style=\"height:11px;width:4px;visibility:hidden;position:absolute;\">' \
.scan(/\d+/) \
.inject{|s,n| Integer(s) + Integer(n)} #returns 15
示例2:
'<div style=\"height:221px;width:47px;\">' \
.scan(/\d+/).inject{|s,n| Integer(s) + Integer(n)} #=>268
它只是选取所有(\d+)
,转换为Integer
并提供Sum
:
css='<div id=\"c_pcnb\" style=\"height:11px;width:4px;visibility:hidden;position:absolute;\">'
css.scan(/\d+/).inject{|s,n| Integer(s) + Integer(n)} #=> 15
答案 1 :(得分:1)
我会这样做:
require 'nokogiri'
doc= Nokogiri::HTML::Document.parse <<-eotl
<div id="c_pcnb" style="height:11px;width:4px;visibility:hidden;position:absolute;">
eotl
hsh = Hash[*doc.at_css('#c_pcnb')['style'].split(/[:;]/)]
# => {"height"=>"11px",
# "width"=>"4px",
# "visibility"=>"hidden",
# "position"=>"absolute"}
(hsh["height"].to_i + hsh["width"].to_i).to_s + 'px'
# => "15px"