Skip to content

Instantly share code, notes, and snippets.

View ktanaka101's full-sized avatar

Kentaro Tanaka ktanaka101

  • Japan
  • 12:03 (UTC +09:00)
View GitHub Profile
@ktanaka101
ktanaka101 / gist:d00495b622433ee2e2059907bc6543f8
Created November 6, 2019 14:39
Replacing Rust code with VSCode
target: &Vec<i64> -> &[i64]
from : &Vec<([^>]*)>
to : &[$1]
fn a(n)
case {n % 3 == 0, n % 5 == 0}
when {true, false}
"Fizz"
when {false, true}
"Buzz"
when {true, true}
"Fizz Buzz"
else
n.to_s
@ktanaka101
ktanaka101 / .cr
Created August 23, 2019 16:46
REP macro for Crystal
macro rep(*args, &block)
{% for iterator, idx in args %}
({{iterator}}).each do |{{block.args[idx].id}}|
{% end %}
{{ block.body }}
{% for i in args %} end {% end %}
end
# same
rep 0...5 do |i|
# crystal
val = 0x80_00_00_00.to_s # => "2147483648"
#val.to_i # Invalid Int32: 68719476721
val.to_i64 # => 2147483648
val = 0x7f_ff_ff_ff.to_s # => 2147483647
val.to_i # => 2147483647
0b_0111_1111_1111_1111_1111_1111_1111_1111 # => 2,147,483,647
# crystal
hs = {
1 => 12,
5 => 31,
0 => 41,
3 => 56,
4 => 21
}
hs.max_of(&.[1]) # => 56
# crystal
def method : String
yield
end
method do
next 10 # => Error in line 6: instantiating 'method()'
# in line 2: type must be String, not Int32
end
# crystal
result = loop do
break 100
end
p result # => 100
result = while true
break 100
end
# crystal
def method : String
loop do
yield
end
"end"
end
result = method do
break 100 == 100 ? 200 : 200.0
# crystal
# https://crystal-lang.org/docs/syntax_and_semantics/blocks_and_procs.html
arr = [1, 2, 3, 4, 5]
def b(arr)
loop do
arr.each do |x|
yield x
end
end
# crystal
[1, 2, 3, 4, 5].each do |i|
p "before #{i}"
next if i == 3
break if i == 4
p "after #{i}"
end
# => before 1
# => after 1