What's the ruby way to parse a string for a single key/value?
Your code is pretty much the Ruby way. If you don't want to use the global $1
, you can use the 2 arg version String#[]
:
match = text[/your username is: (.*)/, 1]
How to split a string into key-value pairs?
Hash[s.scan(/\@\w+/).zip s.split(/\s?\@\w+\s/).drop(1)]
Ruby extract single key value from first block in json
Since log_entries
is an array you can just access the first element and get its created
value.
Assuming the variable result
holds the whole hash (the JSON you parse from the API):
puts result['log_entries'][0]['created']
will print out the first date. Now you might want to guard that for cases where log_entries
empty, so wrap it in a if
:
if result['log_entries'].any?
puts result['log_entries'][0]['created']
end
How to convert this 'hash-like' string to a key value pair
You can change that string to valid JSON
easily and use JSON.parse
then:
require 'JSON'
myvar = '{"myval1"=>"value1","mayval2"=>"value2"}'
hash = JSON.parse(myvar.gsub(/=>/, ': '))
#=> { "myval1" => "value1", "mayval2" => "value2" }
hash['myval1']
#=> "value1"
Ruby convert string to key value hash
Is this what you need?
Hash[@msg_body.scan /([^=]+)=([^&]+)[&$]/]
=> {"longitude"=>"-26.6446",
"region_name"=>"xxxx",
"timezone"=>"US/Central",
"ip"=>"xxxxxxx",
"areacode"=>"xxx",
"metro_code"=>"xxx",
"country_name"=>"United States",
"version"=>"0250303063A",
"serial"=>"133245169991",
"user_agent"=>"Linux 2 XS",
"model"=>"3100X",
"zipcode"=>"23454",
"city"=>"LA",
"region_code"=>"CA",
"latitude"=>" 56.1784",
"displayaspect"=>"16x9",
"country_code"=>"US",
"api_key"=>"xxxxxxx",
"uuid"=>"3489f464-2f9c-9c4c-d7d2-b51b7dd40ce3",
"event"=>"appLoad"}
How do I split text into key-value pairs?
Use split
with an optional second parameter (thanks to @MichaelKohl)
s = 'Author URL: http://somedudeswebsite.me/'
key, value = s.split ': ', 2
puts key
puts value
Output
Author URL
http://somedudeswebsite.me/
Ruby: How to parse a string to pull something out and assign it to a variable
This tutorial really helped me understand how to work with regular expressions in Ruby.
One way to use a regular expression to get the string you want is to replace the stuff you don't want with an empty string.
original_string = "my name is: andrew"
name = original_string.sub(/^my name is: /, '') # => 'andrew'
another_format = "/nick andrew"
name = another_format.sub(/^\/nick /, '') # => 'andrew'
However, that's just string replacement/substitution. The regex is not capturing anyting.
To capture a string using a regular expression, you can use the Ruby match
method:
original_string = "my name is: andrew"
matches = original_string.match /^my name is: (.*)/
name = matches[1] # return the first match
Related Topics
Cannot Load Such File -- Rack/Handler/Puma
Installing Ruby Gem Less-Rails on Windows MAChine Using Therubyracer
Ruby Conditional-Assignment and Private Methods
Is Getting Converted as "\U0092" by Nokogiri in Ruby on Rails
Why Is Uri.Escape() Marked as Obsolete and Where Is This Regexp::Unsafe Constant
Understanding Ruby Splat in Ranges and Arrays
What's the Best Way to Implement Acls to a Rails Application
How to Use Objects with Xsi:Types in Savon
Extract All Urls Inside a String in Ruby
Ruby Create Tar Ball in Chunks to Avoid Out of Memory Error
Run a Command Line with Custom Environment
Where to Put a Before_Filter Shared Between Multiple Controllers
Catching Timeout Errors with Ruby Mechanize