原文地址:http://rubysource.com/ruby-golf/
Ruby golf is the art of writing code that uses as few characters as possible. The idea originates in the world of Perl (where it is, unsurprisingly, known as Perl Golf). As a language, Perl is well suited to this as it has more than its fair share of bizarre constructs and syntactic sugar. Ruby also contains some large dollops of syntactic sugar which makes it suited to the odd round of golf.
Ruby golf 是一种使用尽量少的字符来编写代码的技术。这个想法最初产生于Perl社区(不出意料的成为Perl Golf)。由于Perl拥有一系列奇异的语法结构和特征,所以很适合应用这种技术。Ruby同样包含大量的奇异语法特征,所以也非常适合这种成为Golf的技术。
The obsession with trying to minimise the number of bytes used in a program harks back to a bygone age when memory was at a premium and every byte counted. It doesn’t really have any practical use in today’s world, but this does not mean that it is not still used. Code minimisation can be found in competitions such as the 1k JavaScript competitions and Perl Apocalypse. There are also a number of sites dedicated to the art of Code Golf.
试着减少程序中使用的字节数的想法可以追溯到那个内存昂贵到以每个字节来计费的时代。当下,这种想法并没有多少实际意义,但是很多时候它仍被使用。代码最小化可以在一些比如称作1k JavaScript competitions和Perl Apocalypse的比赛中找到。也有很多网站试着对Code Golf这种技术有所贡献。
There is often a competitve element associated with Code Golf: Hackers try to outdo each other as they strive to find the ‘perfect’ solution. One that achieves the aim of the code but could not possibly be done in fewer characters. I find this to be analagous to mathemticians who search for ‘elegant proofs’ and am reminded of Einstein’s quote “Everything should be made as simple as possible, but not simpler”.
跟Code Golf相关的一个竞争元素是:黑客们总是试图通过找到'完美'解决方案而超越他人。一个人可以完成代码的功能却可能无法用更少的字母实现。我发现这类似一个寻找“最优解”的数学家被爱因斯坦的名言提醒:"任何事情都应该尽可能简单,而不仅仅是简单。"
Unfortunately, the code that is produced is often very difficult to understand as it usually relies on various hacks and shortcuts. In fact, a complimentary game is to try and figure out what the code produced actually does! There is often a thin line between being clever and too clever…
不幸的是,由于过分依赖各种编程技巧,编写出来的代码经常难以理解。实际上,一个免费的游戏是试着找出这段代码真正做的事情。总有一条细线横亘在变的聪明和变得过于聪明之间...
Code Golf has a bit of a marmite reputation – people either love it or hate it, so to try and maintain some balance, I’ve listed a few of the advantages and disadvantes of trying your hand at a round or two:
Code Golf有截然不同的两种名称:喜欢它或者厌恶它。所以为了试着去保持某种平衡,我列举了一些Code Gold的优点和缺点:
If you fancy having a go at some golf, then here are a few tips that can be used to cut your Ruby code down to size and reduce your golfing handicap:
专业提示:
如果你喜欢尝试一下Golf,那么这里有一些小贴士可以用来帮助你减少你的Ruby代码并且减少你在这个过程中遇到的困难。
Mass Assignment
This is an easy one that most people will know, but assigning all your variables at once will help to cut down on code bloat.
1 |
a,b = 1 , 2 |
Create Arrays Using the Shortcut Notation %w
You can create arrays of strings by using the following notation:
1 |
a = %w(a b c) => [ "a" , "b" , "c" ] |
使用缩写记号%w来创建数组
你可以通过这个记号来创建字符串数组
Use the Ternary Operator for Logic
1 |
a> 10 ? "too big" : "fine" |
对一些逻辑判断使用使用三元操作符
Use Chained Ternary Operators for More Complex Logic
1 |
a< 0 ? "no negatives" :(a> 10 ? "too big" : "fine" ) |
对一些更复杂的逻辑判断使用链式的三元操作符
Use Scientific Notation for Numbers
If you need big numbers, then 1e6
is shorter than 1000000
.
使用科学计数法来标识数字
如果你需要很大的数字,那么1e6比1000000要短。
Use Dash-Rocket Syntax for Procs
If you’re using Ruby 1.9, use the dash-rocket (->
) syntax for procs
1 |
sayhello = -> {p "hello" } |
2 |
sayhello = -> name {p "hello #{name}" } |
使用dash-rocket(->)创建proc
如果你使用的是Ruby 1.9,在创建proc结构时使用dash-rocket(->)符号
1 Character Strings
For 1 digit strings, use ?x = "x"
(again, this only works in Ruby 1.9 though)
单字母字符串
对于单字母字符串,可以使用?x 来标识"x"(同样,这个仅适用于Ruby 1.9)
Learn Regular Expressions
Regular expressions can express some complicated expressions in a few characters.
学习正则表达式
正则表达式可以用很少的字符数来替代一些复杂的表达式
Use the Modulo Operator to Test if a Number is a Factor
12%3==0
, because 12 is a multiple of 313%3!=0
, because 13 is not a multiple of 3
**EDIT**
This has been improved further by Cyrus in the comments. You can actually just test if the answer is less than one rather than equal to zero:
1 |
12 % 3 < 1 => true |
使用模操作符去测试一个数字是否是因子
12%3==0,因为12是3的倍数
13%3!=0,因为13不是3的倍数
这个操作已经得到改进。你可以测试这个答案是否小于1去代替是否等于0
12%3<1 => true
Use Map to Iterate
Iterators are usually better than for loops and map
is the best iterator as it has the least characters. It can be used instead of each
because you don’t have to change each element in the array, it still loops through it.
1 |
%w(a b c).map{|x| puts x} |
使用Map去迭代
迭代器通常要比循环好,并且因为map所用的字母最少所以map是最好的迭代器。它可以被用来取代each因为你不需要改变数组中每个元素的值,它仍然会循环一遍。
Use Symbol To Proc
This saves a lot of time (and possibly looks neater).
1 |
%w(a b c).map{ |e| e.upcase } |
becomes
1 |
%w(a b c).map(& :upcase ) |
2 |
=> [ "A" , "B" , "C" ] |
What actually happens is that &
calls the to_proc
method for the symbol that follows (in this case the upcase
method is called on each element of the array.
在Proc中使用名字
这种方法可以节省很多时间(而且可能看上去更整洁)
%w(a b c).map{ |e| e.upcase}
可以写成
%w(a b c).map(&:upcase)
实际上&会使用紧接后面的名字来调用to_proc方法(在这个例子中upcase方法对数组中的每个元素调用)
Easy Joins%w(a b c)*"-"
is the same as %w(a b c).join"-"
=> “a-b-c”
更方便的链接
%w(a b c)*"-" 等同于%w(a b c).join"-"
=> "a-b-c"
Reuse Loops
A good way to avoid using 2 loops for different object types is to bung all the objects into a single array and use just one iterator, but then perform different tasks depending on the object type.
1 |
[ "a" , "b" , 2 , 4 ].map{|e|(e.to_s==e)?(e.upcase):(e* 2 )} |
2 |
=> [ "A" , "B" , 4 , 8 ] |
重用循环
一个避免对不同对象类型使用两个循环的好方法是将所有对象都塞到单独的数组中,然后使用唯一的循环,但是根据对象的类型调用不同的任务。
["a","b",2,4].map{|e|(e.to_s==e)?(e.upcase):(e*2)}
=> ["A","B",4, 8]
Testing Types
If you want to test if an object is a string then e.to_s==e
is shorter than e.is_a? String
.
测试类型
如果你想要测试一个对象是否是字符串,e.to_s==e 要比 e.is_a? String 要短。
Do you have any other tips to bring one’s handicap down? Leave your tips in the comments.
Konstantin Hasse (Sinatra Jedi Grand Master) performed an extreme form of Ruby golf when he condensed Sinatra (not exactly bloated at 1646 lines of code) into a measly 8 lines of code. It didn’t quite have the same functionality, but came pretty darn close. He used some great tricks when doing this, the last couple of tips in the list above are from the Almost Sinatra code.
Almost Sinatra
Konastantin Hasse(Sinatra的绝地一代宗师)诠释了一种Ruby golf的极致形式:他将Sinatra(估计大约有1646行代码)浓缩到了极少的8行代码。确切的讲它并没有完全复制原有功能,但是却相当的接近。在这个过程中,他使用了一些非常棒的技巧,上面列的一些贴士就是来源于Almost Sinatra的代码。
As a example, I tried writing a method that would find the sum of all multiples of a given number up to a given value. For example sum(5,24) would calculate the sum of all the multiples of 5 up to 24 (ie 5 + 10 + 15 + 20).
This is what I came up with in the end:
1 |
def sum(n,t) |
2 |
n*( 1 ..t/n).to_a.inject(&:+) |
3 |
end |
I utilised the symbol to proc notation to use the inject method to sum the integers. How many integers to sum was found by doing integer division and relying on the fact that remainders are ignored.
This contains 27 characters (not including the method definition). Can anybody beat it? Leave your answer in the comments if you can.
一个例子
举个例子,我试着写一个方法,这个方法会找到一个特定数到一个给定值的所有倍数之和。比如,sum(5,24)会计算所有24以内5的倍数之和。
这是我最后的方案:
def sum(n,t)
n*(1..t/n).to_a.inject(&:+)
end
我利用了proc中的名字的标记法并使用了inject的方法来计算所有整数的值。至于有多少整数相加则通过整数除法并忽略余数的方法来保证。
这个方法一共包含了27个字母(不包含方法定义)。有人可以打败它嘛?如果你能的话请再评论区留下你的答案。
Now it’s time to find out who is the Tiger Woods of the Ruby World. Below are five ‘holes’ that make up the RubySource Golf Course. Try your hand at any or all of them and post your solutions in the comments.
竞赛
现在是时候去找出Ruby世界里的Tiger Woods了。下面有五个holes组成了Ruby代码Golf课程。请尝试其中的一些或全部并将你的解决方案列在评论中。
Given a number the function returns “Fizz” if it is a multiple of 3, “Buzz” if it is a multiple of 5 and “FizzBuzz” if it is a multiple of 15. If the number is not a multiple of 3 or 5 then the number is returned as a string.
1 |
fizzbuzz(3) => "Fizz" |
2 |
fizzbuzz(10) => "Buzz" |
3 |
fizzbuzz(45) => "FizzBuzz" |
4 |
fizzbuzz(31) => "31" |
Hold1:
给出一个数,如果这个数是3的倍数,就返回"Fizz",如果是5的倍数就返回"Buzz",如果是15的倍数就返回"FizzBuzz"。如果这个数既不是3的倍数也不睡5的倍数,那么这个数就会作为字符串返回。
例子:
fizzbuzz(3) => "Fizz"
fizzbuzz(10) => "Buzz"
fizzbuzz(45" => "FizzBuzz"
fizzbuzz(31) => "31"
Implement a Caesar Shift Cipher
1 |
caeser( "hello" ,3) => "khoor" |
You should also be able to produce negative shifts.
Hole2:
实现一个凯撒移位密码
例子:
caeser("hello",3) => "khoor"
你应该同样实现逆向转换。
Write a simple method that ‘plays’ this game, where the player enters their ‘move’ as an argument to the method. If the player enters an invalid option then the result should be ‘lose’. The computer should choose its move at random. The output gives the computer’s ‘move’ and the result as a comma-separated string.
1 |
play( "Rock" ) => "Rock,Draw" |
2 |
play( "Paper" ) => "Rock,Win" |
3 |
play( "Scissors" ) => "Rock,Lose" |
4 |
play( "Soap" ) => "Paper,Lose" |
Hold3:
写一个简单的方法来“玩”游戏,游戏里玩家输入他们的“动作”作为参数给这个方法。如果这个玩家输入一个不合法的选项,那么这个结果会是“失败”。计算机会随机选择它的动作。方法的输出会给出计算机的“动作”,这个输出是用逗号分隔的。
Write a method that when given a string and substring, returns the number of times the substring occurs in that string (ignoring case).
1 |
count( "Banana" , "a" ) => 3 |
2 |
count( "RubySource provides advice, tutorials, commentary, and insight into the Ruby and Rails ecosystem" , "ruby" ) => 2 |
Hold4:
写一个方法,当给出一个字符串和一个子串,返回这个子串在这个字符串中出现的次数(忽略字母大小写)。
例子:
count("Banana","a") => 3
count("RubySource provides advice, tutorials, commentary, and insight into the Ruby and Rails ecosystem","ruby") => 2
Write a function that replaces ‘putting your keys in a tin’. The argument to the function is an array of arrays that contain two objects. The function returns a new array where the pairs of objects have been mixed up. An object should not end up with it’s original ‘partner’.
1 |
swingers([[ "Homer" , "Marge" ],[ "Micky" , "Minnie" ],[ "Fred" , "Wilma" ],[ "Peter" , "Lois" ],[ "George" , "Judy" ]]) |
2 |
=> [[ "Homer" , "Wilma" ],[ "Micky" , "Lois" ],[ "Fred" , "Judy" ],[ "Peter" , "Marge" ],[ "George" , "Minnie" ]] |
To enter, write your method in the comments below. The person whose entry contains the lowest number of characters will win each hole. There’s a Sitepoint book up for grabs for the winner of each hole. You can use Ruby 1.8 or 1.9. The deadline is 31st December 2011. Only the characters inside the method definition will be counted, so my example hole above would count as 27 characters. Feel free to post a Gist to your code.
Hole5:
写一个方法来取代‘putting your keys in a tin’。这个方法的参数是一个包含两个对象的数组的数组。这个方法返回一个新的数组,其中成对的对象都已经被混合了。一个对象不能以它原来的“搭档”结尾。
例子:
swingers([["Homer","Marge"],["Micky,"Minnie"],["Fred","Wilma"],["Peter","Lois"],["George","Judy"]])
=>
[["Homer","Wilma"],["Micky","Lois"],["Fred","Judy"],["Peter","Marge"],["George","Minnie"]]
(待续。)