Search code examples
rubystringsplitruby-hash

Ruby RoR split a hash


I have a hash like this :

hash = {"user:**xy@xy.com** password:**azerty**"=>1,
        "user:**yy@yy.com** password:**qwerty**"=>1}

How can I extract only the username (email) and the password of each element to use it separately.

With split method eventually. How to split a string from the second : for example?

I want to have something like this

Username  Password
xy@xy.com azerty
yy@yy.com qwerty

Solution

  • Just one more way to handle the situation:

    hash.keys.to_s.scan(/user:(\w+@\w+.\w+)\spassword:(\w+)/)
    #=> [["xy@xy.com", "azerty"], ["yy@yy.com", "qwerty"]]
    

    Breakdown:

    • hash.keys.to_s - an Array of the keys in the Hash (since we don't care about values) converted to a string "[\"user:xy@xy.com password:azerty\", \"user:yy@yy.com password:qwerty\"]"
    • scan(/user:(\w+@\w+.\w+)\spassword:(\w+)/) - an Array of the matching capture groups

    Example