`
Goldice
  • 浏览: 108135 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[翻译] Ruby Golf

 
阅读更多

原文地址: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

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

 

 

 

(待续。)

 

 

0
0
分享到:
评论

相关推荐

    Ruby-Mobility可拔插的Ruby翻译框架

    Ruby-Mobility是一款强大的、可拔插的Ruby翻译框架,专为解决多语言支持而设计。这个框架的主要目标是提供一种灵活、高效且易于集成的方式来处理应用中的国际化(i18n)问题。Ruby-Mobility的核心设计理念在于解耦...

    Ruby-bladetranslate是一款用ruby打造的简单控制台翻译软件

    Ruby-blade-translate是一款基于Ruby语言开发的轻量级命令行翻译工具,专为那些喜欢在终端环境下工作的开发者设计。它的核心功能是提供一种快速、便捷的方式,在不同的文本之间进行翻译,而无需离开命令行界面。这个...

    Ruby Ruby Ruby Ruby Ruby Ruby

    Ruby Ruby Ruby Ruby Ruby Ruby

    Ruby-Localer自动检测丢失的I18n翻译工具

    Ruby-Localer是一款专为Ruby开发设计的自动化工具,用于检测和管理应用程序中的I18n(国际化)翻译。在软件开发中,I18n是确保应用能在不同语言环境中正常运行的关键步骤,它允许开发者将文本从源代码中分离出来,...

    ruby DBI ruby DBI ruby DBI

    ruby DBI ruby DBI ruby DBIruby DBI ruby DBI ruby DBIruby DBI ruby DBI ruby DBIruby DBI ruby DBI ruby DBIruby DBI ruby DBI ruby DBIruby DBI ruby DBI ruby DBIruby DBI ruby DBI ruby DBIruby DBI ruby DBI ...

    Ruby-rubybuild编译和安装Ruby

    Ruby是一种动态、开源的编程语言,以其简洁、优雅的语法和强大的元编程能力著称。在Ruby开发中,为了管理不同版本的Ruby环境,我们常常会使用到`rbenv`和`ruby-build`这两个工具。本文将详细介绍如何使用`ruby-build...

    ruby-golf:2014 年 11 月巴斯Ruby聚会的Ruby高尔夫球场设置

    Ruby Golf 是一款要求玩家以尽可能少的角色解决许多问题(洞)的游戏。 该课程包括您必须实施的九个洞。 这些Kong是需要为 Golf 类编写的静态方法: lib/golf.rb 。 这些方法的要求由每个球洞的一组 RSpec 示例...

    Ruby完全自学手册 下

    《Ruby完全自学手册》是一本完全覆盖Ruby和Ruby on Rails的完全自学手册。《Ruby完全自学手册》的特色是由浅入深、循序渐进,注重理论和实践的结合。虽然定位为入门手册,但是依然涉及许多高级技术和应用,覆盖到的...

    ruby2ruby.zip

    ruby2ruby 提供一些用来根据 RubyParser 兼容的 Sexps 轻松生成纯 Ruby 代码的方法。可在 Ruby 中轻松实现动态语言处理。 标签:ruby2ruby

    Ruby-rubyinstall安装RubyJRubyRubiniusMagLevorMRuby

    Ruby是一种强大的、面向对象的脚本语言,广泛用于Web开发、服务器端编程和各种应用程序。在Ruby的世界里,管理不同的Ruby实现(如MRI、JRuby、Rubinius、MagLev和MRuby)是非常重要的,这有助于开发者根据项目需求...

    src-oepkgs/ruby-ruby2ruby

    src-oepkgs/ruby-ruby2rubysrc-oepkgs/ruby-ruby2rubysrc-oepkgs/ruby-ruby2rubysrc-oepkgs/ruby-ruby2rubysrc-oepkgs/ruby-ruby2rubysrc-oepkgs/ruby-ruby2rubysrc-oepkgs/ruby-ruby2rubysrc-oepkgs/ruby-ruby2...

    Ruby Under a Microscope An Illustrated Guide to Ruby Internals

    书中解释了Ruby代码是如何被翻译成其他语言的,这个翻译过程通常由一个编译器来完成。理解编译的过程有助于程序员编写出更优化的代码,因为这涉及到性能的许多方面。 作者Pat Shaughnessy是著名的Ruby编程专家和...

    Ruby完全自学手册

    Ruby是一种简洁而功能强大的编程语言,由日本的松本行弘(Yukihiro "Matz" Matsumoto)在1993年开发,并于1995年公开发布。Ruby语言设计之初就非常注重开发人员的编程体验,它拥有自然、表达性强的语法,易于阅读和...

    ruby源代码 ruby源代码 ruby源代码 ruby源代码2

    ruby源代码 ruby源代码 ruby源代码 ruby源代码2

    ruby安装包下载 | ruby环境搭建

    Ruby是一种强大的动态编程语言,广泛应用于Web开发,脚本编写,服务器管理等领域。为了在没有外网连接的环境中搭建Ruby环境,你需要提前下载并准备相关的安装包。在提供的压缩包中,包含了三个关键文件:`ruby-2.7.2...

    Ruby-TensorStream用Ruby重新实现TensorFlow

    **Ruby-TensorStream:用Ruby重现实现TensorFlow** Ruby-TensorStream是一个开源项目,旨在为Ruby开发者提供一个类似于Google TensorFlow的深度学习框架。它的核心目标是让Ruby程序员能够利用TensorFlow的强大功能...

    Ruby资源ruby-v3.1.1.zip

    Ruby是一种面向对象的、动态类型的编程语言,以其简洁、优雅的语法和强大的元编程能力而闻名。本资源“ruby-v3.1.1.zip”包含了Ruby的最新版本3.1.1,这是一个重要的里程碑,因为它引入了新特性、性能优化以及对旧...

    ruby源代码 ruby源代码 ruby源代码 ruby源代码4

    ruby源代码 ruby源代码 ruby源代码 ruby源代码4

    Ruby基础教程(第5版)1

    翻译者何文斯在序言中分享了自己对Ruby的热爱,并指出Ruby的“快乐编程”理念,强调了编程不仅可以是一项技术工作,也可以是一种享受。他相信,通过阅读这本书,读者能够重新发现编程的乐趣,并提升自己的编程技巧。...

    ruby中文手册 chm

    4. **Programming Ruby的翻译**: Programming Ruby是Ruby编程的经典书籍,通常被称为“Pickaxe书”。这本书深入浅出地介绍了Ruby的各个方面,包括语言特性、标准库以及开发工具。中文翻译版可以帮助中文读者更好地...

Global site tag (gtag.js) - Google Analytics