-2

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
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
media
  • 135
  • 1
  • 7

4 Answers4

1

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

engineersmnky
  • 25,495
  • 2
  • 36
  • 52
0

consider below snippet. it will give you a view, that you'll know, where you should start.

h.keys().map {|x| x.split(" ")}.each do |e|
  puts "#{e.first.split(":").last}   #{e.last.split(":").last}"
end

# xy@xy.com   azerty
# yy@yy.com   qwerty
marmeladze
  • 6,468
  • 3
  • 24
  • 45
0
hash.each { |x,y| puts x.split(" ").to_s.gsub("user:", "").to_s.gsub("password:", "") }
# ["xy@xy.com", "azerty"]
# ["yy@yy.com", "qwerty"]
Alejandro Montilla
  • 2,626
  • 3
  • 31
  • 35
  • 1
    Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) of *how* it addresses the question. Without that, your answer has much less educational value - remember that you are answering the question for readers in the future, not just the person asking now! Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight May 03 '17 at 15:08
0

Make use of Split

hash.each do |key, _val|
  puts key.split.map { |s| s.split(':').last }.join(' ')
end
Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88