原文地址: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的优点和缺点:

Advantages

  • You get to learn some lesser known parts of the language and some neat tricks.
  • You get a nice smug feeling inside when you manage to chip a few more characters off the best solution.
  • Sometimes the more succinct way of writing the code actually looks cleaner.
  • You can learn techniques that could be of use in other situtations.
  • The process itself encourages ingenuity.
  • It’s fun!
优点:
1. 你会学到这门语言的一些很少人知道的部分和一些优雅的技巧
2. 当你试着减少最佳解决方案的代码你会得到快感
3. 有时候更简洁的代码看上去的确更干净
4. 你可以学到能够在其他环境中使用的技术
5. 这个过程鼓励你发挥聪明才智
6. 有乐趣!

Disadvantages

  • The code usually looks horrible
  • The code can often be difficult to read or understand, which is a shame because one of the best aspects of Ruby is how readable it is.
  • The code would be a maintenance nightmare – even by yourself never mind others.
缺点:
1. 代码很有可能看起来畏惧
2. 代码经常比较难于理解或者阅读,这真是强调可读性的Ruby代码的一个耻辱啊
3. 代码真是维护者的噩梦——即便是你自己来维护

Pro Tips

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

view source print?
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 3
13%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"48]

重用循环

一个避免对不同对象类型使用两个循环的好方法是将所有对象都塞到单独的数组中,然后使用唯一的循环,但是根据对象的类型调用不同的任务。

["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.

你还有其他的建议解决问题吗?在评论中留下你的建议吧。

Almost Sinatra

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的代码。

An Example Hole

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个字母(不包含方法定义)。有人可以打败它嘛?如果你能的话请再评论区留下你的答案。

Competition

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课程。请尝试其中的一些或全部并将你的解决方案列在评论中。

Hole 1: Fizz Buzz

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.

Example:

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"

Hole 2: Caesar Cipher

Implement a Caesar Shift Cipher

Example:

1 caeser("hello",3) => "khoor"

You should also be able to produce negative shifts.

Hole2:

实现一个凯撒移位密码

例子:

caeser("hello",3) => "khoor"

你应该同样实现逆向转换。

Hole 3: Rock,Paper,Scissors Game

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.

Example:

1 play("Rock") => "Rock,Draw"
2 play("Paper") => "Rock,Win"
3 play("Scissors") => "Rock,Lose"
4 play("Soap") => "Paper,Lose"

Hold3:

写一个简单的方法来“玩”游戏,游戏里玩家输入他们的“动作”作为参数给这个方法。如果这个玩家输入一个不合法的选项,那么这个结果会是“失败”。计算机会随机选择它的动作。方法的输出会给出计算机的“动作”,这个输出是用逗号分隔的。

Hole 4: String Counter

Write a method that when given a string and substring, returns the number of times the substring occurs in that string (ignoring case).

Example:

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

Hole 5: Swingers Function

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’.

Example:

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"]]

(待续。)

[翻译] Ruby Golf相关推荐

  1. 发福利:整理了一份关于“资源汇总”的汇总

    觉得有用的话,可以去github关注:https://github.com/justjavac/awesome-awesomeness-zh_CN 一份关于"资料汇总"的汇总. 通 ...

  2. 发福利,整理了一份关于“资源汇总”的汇总

    觉得有用的话,可以去github关注:https://github.com/justjavac/awesome-awesomeness-zh_CN 通用 free-programming-books- ...

  3. 在AWS Lambda上运行脚本语言:PHP、Ruby和Go(外文翻译)

    本文来自Mobingi官方技术专栏,欢迎关注 本文翻译自Scripting Languages for AWS Lambda: Running PHP, Ruby, and Go 备注:Go已经在20 ...

  4. 【翻译】在ruby中实现attributes的lazily initialization(惰性初始化)

    [翻译]Ruby: Lazily Initialized Attributes url(注:原文网址访问不到,估计是被和谐了): http://blog.jayfields.com/2007/07/r ...

  5. ruby操作常用数据库 - 使用DBI[翻译 转帖]

    使用Ruby DBI模块 原著 Paul DuBois   paul@kitebird.com 翻译:liubin  2004/11/9  http://www.ruby-cn.org/   原文地址 ...

  6. 【翻译】Programming Ruby——正则表达式

    正则表达式 Ruby大部分的内置类型都和其它的编程语言很相似.主要有strings,integers,floats,arrays等等.然而,只有脚本语言, 如Ruby,Perl,和awk等提供了内置表 ...

  7. 【翻译】Programming Ruby——数组,哈希表和控制结构

    数组和哈希表 Ruby的数组和哈希表是索引集合.两都都是保存对象集合并能通过键来读取.数组的键是数字,但是哈希表则支持对象作为键.它们都是随着新元素的加入要增长.在访问元素方面,数组效率比较高,但哈希 ...

  8. Ruby DSL介绍及其在测试数据构造中的使用(2)

    在(1)中介绍了DSL和普通的函数定义之间的区别.在(1)的最后提到,DSL分为内部DSL和外部DSL,我们再看一遍他们的定义:1. External DSLs 用不同于host语言的语言来编写,通过 ...

  9. ruby 新建对象_Ruby面向对象编程的简介

    ruby 新建对象 by Saul Costa 由Saul Costa Object-oriented programming (OOP) is a programming paradigm orga ...

最新文章

  1. 新装myeclispse8.6GA、@Override出错
  2. python变量类型怎么决定的_如何确定python中变量的数据类型
  3. python使用base64编码解码数据
  4. C# 运算符及条件控制语句
  5. python中的数据类型和常用运算符
  6. 【Git】Git-常用命令备忘录(三)
  7. CentOS 7 中firewall-cmd命令
  8. 提示未检测到 oracle,Oracle RAC [INS-40406] 未检测到现有的 Oracle Grid Infrastructure 软件...
  9. LINQPad工具-linq、sql、IL优化和转换
  10. Python 读入Excel表时如何判空NaN
  11. Linux的文件权限与目录配置
  12. wxpython日期控件_使用wxpython控件在面板中的位置
  13. 含重根的三阶实对称矩阵的快速对角化方法
  14. latex里图片大小如何调整_LATEX图片位置调整
  15. Android 图片文件读取
  16. 猎头职场:为什么你职场总碌碌无为
  17. QT::QBitArray
  18. 定时器0 定时器2波特率发生器 AD转换
  19. 导数在梯度下降算法中的意义理解
  20. java跳格子不同跳发_(算法)跳格子

热门文章

  1. Opencv-python 图像处理基础知识
  2. 深度学习(5)感知机(神经元)与神经网络
  3. mysql版本不一致会导致uuid_MySQL性能优化和高可用架构建议
  4. python数据框 命名_Python-根据列值将数据框分为多个数据框,并用这些值命名 - python...
  5. Unity初学Shadergraph创建着色器学习教程
  6. gprof 性能优化工具
  7. git用户文档1 — git基础
  8. 线程互斥和同步-- 互斥锁
  9. Spring基础面试题(一)
  10. BASE64 编码和解码