Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created September 1, 2011 10:57
Show Gist options
  • Select an option

  • Save pasberth/1185940 to your computer and use it in GitHub Desktop.

Select an option

Save pasberth/1185940 to your computer and use it in GitHub Desktop.
Ruby の end をなくす!!!!
# -*- coding: utf-8 -*-
module EndlessRuby
def blank_line? line
return true unless line
(line.chomp.gsub /\s+?/, '') == ""
end
def indent line, level, indent=" "
"#{indent * level}#{line}"
end
def indent_count line, indent=" "
return 0 unless line
if line =~ /^#{indent}(.*?)$/
1 + (indent_count $1, indent)
else
0
end
end
def endless_ruby_to_pure_ruby src
lines = src.split "\n"
base_indent_depth = indent_count lines.first, " "
i = 0
loop do
line = lines[i]
currently_indent_depth = indent_count line, " "
j = 1
while lines[i - j] && blank_line?(lines[i - j])
j += 1
end
just_before_indent_depth = indent_count lines[i-j], " "
j = 1
while lines[i - j] && blank_line?(lines[i + j])
j += 1
end
just_after_indent_depth = indent_count lines[i+j], " "
(currently_indent_depth - just_after_indent_depth - base_indent_depth).times do |n|
lines.insert (i += 1), (indent "end", (currently_indent_depth - 1 - n), " ")
end
i += 1
break if lines.length == i
end
lines.join "\n"
end
end
if __FILE__ == $PROGRAM_NAME
require "test/unit"
class TestEndlessRuby < Test::Unit::TestCase
include EndlessRuby
def setup
end
def test_blank_line
assert_equal true, (blank_line? " ")
end
def test_not_blank_line
assert_equal false, (blank_line? " pass")
end
def test_1
input_src = <<DEFINE
def test
test
DEFINE
output_src = <<DEFINE
def test
test
end
DEFINE
output_src.chomp!
assert_equal output_src, (endless_ruby_to_pure_ruby input_src)
end
def test_2
input_src = <<DEFINE
class Test
def test
proc do |args|
pass
proc do |args|
pass
DEFINE
output_src = <<DEFINE
class Test
def test
proc do |args|
pass
end
proc do |args|
pass
end
end
end
DEFINE
output_src.chomp!
assert_equal output_src, (endless_ruby_to_pure_ruby input_src)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment