Skip to content

Instantly share code, notes, and snippets.

@brianm
Created March 28, 2011 19:04
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 brianm/891050 to your computer and use it in GitHub Desktop.
Save brianm/891050 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
t = <<-EOT
#!/usr/bin/env ruby
if 1+1 == 2
puts "hello world"
end
EOT
# what one liner replaces '.gsub /^\s*/, "' to make this output "win"
s = <<-EOB.gsub /^\s*/, ""
#!/usr/bin/env ruby
if 1+1 == 2
puts "hello world"
end
EOB
if t == s
puts "win"
else
puts "lose"
end
@davidsklar
Copy link

s = t.outdent via "gem install outdent" ? :)

(you don't want #!/usr/bin/env ruby automatically converted to #!ruby, right?)

@tcurdt
Copy link

tcurdt commented Mar 28, 2011

Do you want to remove the indent? ...or change the header? ...or both?

EOB.gsub(/^\s{2}/,'').gsub(/^#!.*ruby/, "#!ruby")

works.

Of course using the gem as David already suggested is better to remove the indent. But that does not solve the puzzle ;) I would shoot for...

EOB.outdent.gsub(/^#!.*ruby/, "#!ruby")

@brianm
Copy link
Author

brianm commented Mar 29, 2011 via email

@brianm
Copy link
Author

brianm commented Mar 29, 2011

The #! line was a red herring, nt actually looking to solve that, just outdent!

@brianm
Copy link
Author

brianm commented Mar 29, 2011

outdent solves it, but invokoed a monkeypatch based library :-(

@tcurdt -- legal, but weak, relies on the 2 spaces :-)

@martint
Copy link

martint commented Mar 29, 2011

EOB.split(/^(\s*)/, 2).drop(1).each_slice(2).map { |prefix, text| text.gsub(/^#{prefix}/, '') }.first

@martint
Copy link

martint commented Mar 29, 2011

A better one:

EOB.scan(/^(\s*)(.*)/m).map { |prefix, text| text.gsub(/^#{prefix}/, '') }.first

@martint
Copy link

martint commented Mar 29, 2011

And the simplest one I could come up with... It takes advantage of the side-effects of matching regexes (matched groups go into $1, $2, ...):

EOB.gsub(/^(\s*)(.*)/m, '\2').gsub(/^#{$1}/, '')

@tcurdt
Copy link

tcurdt commented Mar 29, 2011

+1 for martint's last version

what a weird problem though :)

@brianm
Copy link
Author

brianm commented Mar 29, 2011

Impressive!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment