Ruby diff two strings and make an array of the parts that are the same -


with ruby, how can diff between 2 strings, use identical parts base split rest?

for example, have 2 strings (not strings have formatting):

string1 = "computer: person1, title: king, phone: 555-1212" string2 = "computer: personb, title: queen, phone: 123-4567" 

i able compare (diff) 2 strings result:

["computer: ",", title:",", phone:"] 

then use reparse original strings get:

["person1","king","555-1212"] , ["personb","queen","123-4567"] 

which label in db/storage former array.

are there features , how achieve these results?

the object of not need prior knowledge of formatting. way data analyzed patterning , divided such. may comma delimited, new lines, spaced out, etc.

i looking @ gem "diffy" , "diff-lcs" see if might split up.

i think need hash, hash can fancy.

>> string1 = "computer: person1, title: king, phone: 555-1212" >> = string1.gsub(/[^\s\:]/) { |w| "\"#{w}\"" } >> a.insert(0, "{") >> a.insert(-1, "}") >> a1 = json.parse(a) >> #=> {     "computer" => "person1",     "title" => "king",     "phone" => "555-1212"    } 

then can request want in question, like

>> a1["computer"] >> #=> "person1" 

add

and can abstract method further

def str_to_hash(str)   ouput = str.gsub(/[^\s\:]/) { |w| "\"#{w}\"" }   output.insert(0, "{").insert(-1, "}")   json.parse(out) end  >> h2 = str_to_hash(string2) >> h2["computer"] >> #=>"personb" 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -