Parsing a JSON string in Ruby

This looks like JavaScript Object Notation (JSON). You can parse JSON that resides in some variable, e.g. json_string, like so: require ‘json’ JSON.parse(json_string) If you’re using an older Ruby, you may need to install the json gem. There are also other implementations of JSON for Ruby that may fit some use-cases better: YAJL C Bindings … Read more

Why doesn’t Ruby support i++ or i–​ (increment/decrement operators)?

Here is how Matz(Yukihiro Matsumoto) explains it in an old thread: Hi, In message “[ruby-talk:02706] X++?” on 00/05/10, Aleksi Niemelä <aleksi.niemela@cinnober.com> writes: |I got an idea from http://www.pragprog.com:8080/rubyfaq/rubyfaq-5.html#ss5.3 |and thought to try. I didn’t manage to make “auto(in|de)crement” working so |could somebody help here? Does this contain some errors or is the idea |wrong? (1) … Read more

Ruby class instance variable vs. class variable

Instance variable on a class: class Parent @things = [] def self.things @things end def things self.class.things end end class Child < Parent @things = [] end Parent.things << :car Child.things << :doll mom = Parent.new dad = Parent.new p Parent.things #=> [:car] p Child.things #=> [:doll] p mom.things #=> [:car] p dad.things #=> [:car] … Read more

class

First, the class << foo syntax opens up foo‘s singleton class (eigenclass). This allows you to specialise the behaviour of methods called on that specific object. a=”foo” class << a def inspect ‘”bar”‘ end end a.inspect # => “bar” a=”foo” # new object, new singleton class a.inspect # => “foo” Now, to answer the question: … Read more