Why not defined Kernal#to_json use JSON.build(&) directly?

Check following source code.

It defined by use #to_json(IO), then in that method, use JSON.build(io, &)

why not use JSON.build(&) directly like following?

def to_json : String
  JSON.build do |b|
     to_json(b)
  end
end

Because JSON.build doesn’t return a string.

Following is example come from API docs.

require "json"

string = JSON.build do |json|
  json.object do
    json.field "name", "foo"
    json.field "values" do
      json.array do
        json.number 1
        json.number 2
        json.number 3
      end
    end
  end
end

p typeof(string) # => String

Ahh rip, was looking at the one that takes an IO. In the end I don’t think it matters much because this version still uses String.build under the hood so :person_shrugging:.

In the end I don’t think it matters much because this version still uses String.build under the hood

Yes, i see, that my question, if don’t think it matters, why we create a JSON.build(&) method which only wrap String.build?

Probably just convenience, for when you just want to build a JSON string without forcing the user to end up using String.build themselves.

1 Like

Aha, perhaps this really not a big deal, when i do rename refactor, i find this issue, those duplicate code in Kernel#to_json and JSON.build maybe give better performance.