Working with JSON in Ruby

Here’s how to work with JSON in Ruby.

To parse JSON to Ruby objects

We can use JSON.parse() method as follow:

#JSON Parsing example
require "rubygems"
require "json"
string = '{"desc":{"someKey": "someValue", "anotherKey": "value" } ,"main_item": {"stats":{"a":8,"b":12,"c":10}}}'
parsed = JSON.parse(string) # returns a hash
p parsed["desc"]["someKey"]

To dumps/generate JSON from Ruby object

we can use JSON.generate() method as follow:

require 'json' 
my_hash = {:hello => "goodbye"} 
puts JSON.generate(my_hash) 
# ouput will be "{\"hello\":\"goodbye\"}" 

Our Awesome Tools


Compare string to regex in rspec?

Compare string to regex in rspec?

I was doing
expect(@link.url_address == 'abc').to be_true

but url_address might have other text after abc so I am trying
expect(@link.url_address =~ 'abc').to be_true

but I am getting
Failure/Error: expect(@link.url_address =~ /abc/).to be_true
   expected  to respond to `true?`

I also tried
expect(@link.url_address).to =~ /abc/

but I get
 Failure/Error: expect(@link.url_address).to =~ /abc/
   The expect syntax does not support operator matchers, so you must pass a matcher to `#to`.


Answer 1:

Try this:

expect(@link.url_address).to match(/abc/)