public
Created

ruby-golf

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
# using Ruby 1.9.2
 
# Hole 1, 41 chars
def fizzbuzz(n)
"#{n%3<1&&f=:Fizz;n%5<1?"#{f}Buzz":f||n}"
end
# Same as Cyrus's solution, optimized
 
p fizzbuzz(3) # => "Fizz"
p fizzbuzz(10) # => "Buzz"
p fizzbuzz(45) # => "FizzBuzz"
p fizzbuzz(31) # => "31"
 
# ----------------
# Hole 2, 39 chars
def caesar(s,i)
s.bytes.map{|b|97+(b-97+i)%26}.pack'c*'
end
# One more of the same length:
# s.bytes.map{|b|(97+(b-97+i)%26).chr}*''
 
p caesar("hello",3) # => "khoor"
p caesar("hello",0) # => "hello"
p caesar("khoor",-3) # => "hello"
 
# ----------------
# Hole3, 91 chars
def play(f)
m=%w(Rock Paper Scissors);c=rand(3);u=m.index(f)||c-1;[m[c],%w(Draw Win Lose)[(u-c)%3]]*','
end
 
p play("Rock") # => "Rock,Draw"
p play("Paper") # => "Rock,Win"
p play("Scissors") # => "Rock,Lose"
p play("Soap") # => "Paper,Lose"
 
# ----------------
# Hole 4, 33 chars
def counter(s,i)
s.scan(/#{Regexp.quote i}/i).size
end
# This is sufficient if only alphanumeric chars allowed:
# s.scan(/#{i}/i).size
 
p counter("Banana","a") # => 3
p counter("RubySource provides advice, tutorials, commentary, and insight into the Ruby and Rails ecosystem","ruby") # => 2
 
# ----------------
# Hole 5, 38 chars
def swingers(a)
x,y=a.shuffle.transpose;x.zip y.rotate
end
 
p swingers([["Homer","Marge"],["Micky","Minnie"],["Fred","Wilma"],["Peter","Lois"],["George","Judy"]])
# => [["Homer","Wilma"],["Micky","Lois"],["Fred","Judy"],["Peter","Marge"],["George","Minnie"]]

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.