Skip to content

Instantly share code, notes, and snippets.

@maiha
Last active June 22, 2018 01:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maiha/1f9dcb4ce36d61fd1884dfac1026e0fd to your computer and use it in GitHub Desktop.
Save maiha/1f9dcb4ce36d61fd1884dfac1026e0fd to your computer and use it in GitHub Desktop.

[OK] 1.rb

require "json"

def convert_to_json(obj)
  obj.to_json
end

p convert_to_json(1)   # => "1"
p convert_to_json("x") # => "\"x\""
% ruby 1.rb
"1"
"\"x\""

% crystal 1.rb
"1"
"\"x\""

[NG] 2.rb

require "json"

def convert_to_json(obj)
  obj.to_json
end

p convert_to_json(/x/)
% ruby 2.rb
"\"(?-mix:x)\""

% crystal build 2.rb
...
in /usr/share/crystal/src/json/to_json.cr:10: no overload matches 'Regex#to_json' with type JSON::Builder
Overloads are:
 - Object#to_json(io : IO)
 - Object#to_json()

      to_json(json)

3.cr

module Jsonable
  abstract def to_json : String
end

def convert_to_json(obj : Jsonable)
  obj.to_json
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment