Skip to content

Instantly share code, notes, and snippets.

@amadanmath
Created November 22, 2011 05:23
Show Gist options
  • Save amadanmath/1384966 to your computer and use it in GitHub Desktop.
Save amadanmath/1384966 to your computer and use it in GitHub Desktop.
Ruby Golf
# Written against Ruby 1.9.2
# Hole #1: FizzBuzz
# I accidentally saw Cyrus's solution before trying my own, so no attempt
# Hole #2: Caesar Cipher
# Works only for `[a-zA-Z]*`
def caesar(f,x)
f.each_char.map{|c|t=c.ord+x;(t-1)&31>25&&t+=x<0?26:-26;t.chr}*''
end
# Hole #3: String Counter
def count(f,s)
f.scan(/#{Regexp.quote(s)}/i).size
end
# Hole #4: Rock-Paper-Scissors
# Anyone know why I can't remove the space before the first `?`?
def play(f)
m=%w(Rock Paper Scissors);c,h=rand(3),m.index(f);m[c]+','+(h==c ?'Draw':(!h||h!=(c+1)%3?'Lose':'Win'))
end
# Hole #5: Swingers
# For a trivial (non-random) solution, remove `s.shuffle!;`
def swingers(s)
s.shuffle!;x,y=s.transpose;y<<y.shift;s.each{|t|t[1]=y.shift}
end
puts caesar("hello", 3)
puts caesar("khoor", -3)
puts caesar("abcxyz", 1)
puts caesar("abcxyz", -1)
puts count("banana", "a")
puts count("RubySource provides advice, tutorials, commentary, and insight into the Ruby and Rails ecosystem","ruby")
puts swingers([["Homer","Marge"],["Micky","Minnie"],["Fred","Wilma"],["Peter","Lois"],["George","Judy"]]).inspect
puts play("Rock")
puts play("Paper")
puts play("Scissors")
puts play("Soap")
@cookrn
Copy link

cookrn commented Nov 26, 2011

I had trouble with the ternary operators as well re: your comment on L18. I believe the interpreter is looking for a variable/function called c? at that point since ?s are valid chars for those. Nice work! Mine are here.

@amadanmath
Copy link
Author

Oh, you're right! Welp, one mystery solved. Even nicer work - mine aren't as tight!

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