Last active
March 5, 2021 22:59
-
-
Save JoshCheek/fa6768c4d4363cf54c663b5fe24b272d to your computer and use it in GitHub Desktop.
Who even needs types anyway?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This fixes a bug that the code below triggered. SiB uses String#<< on this line: | |
# https://github.com/JoshCheek/seeing_is_believing/blob/46d49a53a68ec22edd52322ad0f1192ef2d77f51/lib/seeing_is_believing/event_stream/producer.rb#L155 | |
# So it should include this alias in the Safe refinements here: | |
# https://github.com/JoshCheek/seeing_is_believing/blob/46d49a53a68ec22edd52322ad0f1192ef2d77f51/lib/seeing_is_believing/safe.rb#L47-L51 | |
module SeeingIsBelieving::Safe | |
refine String do | |
alias << << | |
end | |
end | |
require 'json' | |
class String | |
def to_num | |
Integer self rescue Float self rescue JSON.parse self rescue raise TypeError, "Can't convert #{inspect} into a number!" | |
end | |
num = -> name, next_method do | |
define_method(name) { |*ords, **kws, &blk| to_num.public_send(name, *ords, **kws, &blk).public_send(next_method) } | |
end | |
%i[divmod coerce to_int].each { |name| num[name, :itself] } | |
%i[-@ +@ ~ + - / * ** ^ << >> []].each { |name| num[name, :to_s] } | |
end | |
# Omg, its brilliant, we don't have to care about types anymore! Someone tell Rails! | |
1 + '2' # => 3 | |
'1' + 2 # => "3" | |
# Integer division! Float division! String division! | |
'10' / 4 # => "2" | |
'10' / 4.0 # => "2.5" | |
'10.0' / 4 # => "2.5" | |
'10' / '4' # => "2" | |
'10' / '4.0' # => "2.5" | |
# Sleeptastic! | |
Time.now # => 2021-03-05 16:57:36.010799 -0600 | |
sleep "2" | |
Time.now # => 2021-03-05 16:57:38.015985 -0600 | |
# Addable! Negatable! (not concatenatable) | |
'12' + '23' # => "35" | |
-'123' # => "-123" | |
# Bitwise operatable! | |
"%b" % ( ~'0b1100110011001100' # => "-52429" | |
) # => "..10011001100110011" | |
# Arrayable, Hashable, Indexable! | |
"[11, 22, 33]"["1"] + '{"a": "44", "b": "55"}'["a"] # => "66" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment