`

ruby使用技巧

阅读更多
翻出来一篇很老的东西,有些已经不用了,总之,抄回来,看看吧

1 - Extract regular expression matches quickly

A typical way to extract data from text using a regular expression is to use the match method. There is a shortcut, however, that can take the pain out of the process:

email = "Fred Bloggs <fred@bloggs.com>"
email.match(/<(.*?)>/)[1]            # => "fred@bloggs.com"
email[/<(.*?)>/, 1]                  # => "fred@bloggs.com"
email.match(/(x)/)[1]                # => NoMethodError [:(]
email[/(x)/, 1]                      # => nil
email[/([bcd]).*?([fgh])/, 2]        # => "g"


Ultimately, using the String#[] approach is cleaner though it might seem more "magic" to you. It's also possible to use it without including an extra argument if you just want to match the entire regular expression. For example:

x = 'this is a test'
x[/[aeiou].+?[aeiou]/]    # => 'is i'


In this example, we match the first example of "a vowel, some other characters, then another vowel."
2 - Shortcut for Array#join

It's common knowledge that Array#*, when supplied with a number, multiplies the size of the array by using duplicate elements:

[1, 2, 3] * 3 == [1, 2, 3, 1, 2, 3, 1, 2, 3]


It's not well known, however, that when given a string as an argument Array#* does a join!

%w{this is a test} * ", "                 # => "this, is, a, test"
h = { :name => "Fred", :age => 77 }
h.map { |i| i * "=" } * "\n"              # => "age=77\nname=Fred"


3 - Format decimal amounts quickly

Formatting floating point numbers into a form used for prices can be done with sprintf or, alternatively, with a formatting interpolation:
money = 9.5
"%.2f" % money                       # => "9.50"


4 - Interpolate text quickly

The formatting interpolation technique from #3 comes out again, this time to insert a string inside another:

"[%s]" % "same old drag"             # => "[same old drag]"


You can use an array of elements to substitute in too:

x = %w{p hello p}
"<%s>%s</%s>" % x                    # => "<p>hello</p>"


5 - Delete trees of files

Don't resort to using the shell to delete directories. Ruby comes with a handy file utilities library called FileUtils that can do the hard work:

require 'fileutils'
FileUtils.rm_r 'somedir'


Be careful how you use this one! There's a FileUtils.rm_rf too..
6 - Exploding enumerables

* can be used to "explode" enumerables (arrays and hashes). "Exploding" is sort of an implicit on-the-fly conversion from an array to regular method arguments. We'll let the examples do the talking:

a = %w{a b}
b = %w{c d}
[a + b]                              # => [["a", "b", "c", "d"]]
[*a + b]                             # => ["a", "b", "c", "d"]

a = { :name => "Fred", :age => 93 }
[a]                                  # => [{:name => "Fred", :age =>93}]
[*a]                                 # => [[:name, "Fred"], [:age, 93]]

a = %w{a b c d e f g h}
b = [0, 5, 6]
a.values_at(*b).inspect              # => ["a", "f", "g"]


8 - Using non-strings or symbols as hash keys

It's rare you see anyone use non-strings or symbols as hash keys. It's totally possible though, and sometimes handy (and, no, this isn't necessarily a great example!):

does = is = { true => 'Yes', false => 'No' }
does[10 == 50]                       # => "No"
is[10 > 5]                           # => "Yes"


9 - Use 'and' and 'or' to group operations for single liners

This is a trick that more confident Ruby developers use to tighten up their code and remove short multi-line if and unless statements:

queue = []
%w{hello x world}.each do |word|
  queue << word and puts "Added to queue" unless word.length <  2
end
puts queue.inspect


# Output:
#   Added to queue
#   Added to queue
#   ["hello", "world"]

2009 Update: Be careful here - this one can sting you in the butt if your first expression returns nil even when it works. A key example of this is with the puts method which returns nil even after printing the supplied arguments.
10 - Do something only if the code is being implicitly run, not required

This is a very common pattern amongst experienced Ruby developers. If you're writing a Ruby script that could be used either as a library OR directly from the command line, you can use this trick to determine whether you're running the script directly or not:

if __FILE__ == $0
  # Do something.. run tests, call a method, etc. We're direct.
end


11 - Quick mass assignments

Mass assignment is something most Ruby developers learn early on, but it's amazing how little it's used relative to its terseness:

a, b, c, d = 1, 2, 3, 4


It can come in particularly useful for slurping method arguments that have been bundled into an array with *:

def my_method(*args)
  a, b, c, d = args
end

If you want to get really smart (although this is more 'clever' than truly wise):

def initialize(args)
  args.keys.each { |name| instance_variable_set "@" + name.to_s, args[name] }
end


12 - Use ranges instead of complex comparisons for numbers

No more if x > 1000 && x < 2000 nonsense. Instead:

year = 1972
puts  case year
        when 1970..1979: "Seventies"
        when 1980..1989: "Eighties"
        when 1990..1999: "Nineties"
      end


13 - Use enumerations to cut down repetitive code

Rubyists are often keen to remove repetition - often espousing "DRY" (Don't Repeat Yourself). You can take this to extremes using Ruby's enumerators to perform similar operations multiple times. Consider requiring multiple files, for instance:

%w{rubygems daemons eventmachine}.each { |x| require x }


14 - The Ternary Operator

Another trick that's usually learned early on by Ruby developers but rarely in less experienced developers' code is the "ternary operator." The ternary operator is not a fix-all, but it can sometimes make things tighter, particularly in view templates.

puts x == 10 ? "x is ten" : "x is not ten"

# Or.. an assignment based on the results of a ternary operation:
LOG.sev_threshold = ENVIRONMENT == :development ? Logger::DEBUG : Logger::INFO

15 - Nested Ternary Operators

It can be asking for trouble but ternary operators can be nested within each other (after all, they only return objects, like everything else):

qty = 1
qty == 0 ? 'none' : qty == 1 ? 'one' : 'many'
# Just to illustrate, in case of confusion:
(qty == 0 ? 'none' : (qty == 1 ? 'one' : 'many'))


16 - Fight redundancy with Ruby's "logic" features

I commonly see methods using this sort of pattern:

def is_odd(x)
  # Wayyyy too long..
  if x % 2 == 0
    return false
  else
    return true
  end
end


Perhaps we can use a ternary operator to improve things?

def is_odd(x)
  x % 2 == 0 ? false : true
end

It's shorter, and I've seen that pattern a lot (sadly) but you should go one step further and rely on the true / false responses Ruby's comparison operators already give!

def is_odd(x)
  # Use the logical results provided to you by Ruby already..
  x % 2 != 0
end


Sometimes, though, you want to explicitly convert implicit true/false scenarios into explicit true/false results:

class String
  def contains_digits
    self[/\d/] ? true : false
  end
end


If we hadn't done this, you'd get back either nil or the first matched digit rather than true or false.
17 - See the whole of an exception's backtrace

def do_division_by_zero; 5 / 0; end
begin
  do_division_by_zero
rescue => exception
  puts exception.backtrace
end


18 - Allow both single items AND arrays to be enumerated against

# [*items] converts a single object into an array with that single object
# of converts an array back into, well, an array again
[*items].each do |item|
  # ...
end

19 - Rescue blocks don't need to be tied to a 'begin'

def x
  begin
    # ...
  rescue
    # ...
  end
end

def x
  # ...
rescue
  # ...
end


20 - Block comments

I tend to see this in more 'old-school' Ruby code. It's surprisingly under-used though, but looks a lot better than a giant row of pound signs in many cases:

puts "x"
=begin
  this is a block comment
  You can put anything you like here!

  puts "y"
=end
puts "z"

2009 Update: Curiously, I've not seen any significant uptake of block comments in Ruby but.. I don't use them myself either anymore. I suspect with column editing and keyboard shortcuts in common text editors, the motivation here has lessened.
21 - Rescue to the rescue

You can use rescue in its single line form to return a value when other things on the line go awry:

h = { :age => 10 }
h[:name].downcase                         # ERROR
h[:name].downcase rescue "No name"        # => "No name"
分享到:
评论

相关推荐

    Ruby的25个编程细节(技巧、实用代码段)

    ### Ruby的25个编程细节(技巧、实用代码段) #### 1. 使用 `try` 方法处理潜在的异常 在Ruby中,`try` 方法是一个非常有用的功能,它允许我们安全地访问对象的方法或属性,即使该对象为 `nil` 也不会抛出异常。...

    Ruby-Ruby技巧惯用Ruby重构和最佳实践

    一、Ruby技巧 1. 块和迭代器:Ruby中的块(blocks)和迭代器(iterators)是其强大之处。使用`each`、`map`等方法可以简洁地遍历集合。例如,`array.each { |item| puts item }`用于打印数组的所有元素。 2. 魔术...

    ### Ruby介绍、使用技巧和经典案例

    ### Ruby介绍、使用技巧和经典案例 #### 一、Ruby的基本概念 - **简洁灵活**:Ruby语言的设计理念强调简洁性和灵活性。它采用了一种直观且易于理解的语法,允许开发者使用较少的代码来实现复杂的功能。这种简洁性...

    ruby技巧

    在 Ruby 中,程序员可以利用各种技巧来提高代码的可读性和效率。本文将深入探讨 Ruby 中的常值,包括数值、符号、字符串和正则表达式。 1. 数值 - 整数:Ruby 支持两种整数类型——Fixnum 和 Bignum。Fixnum 用于...

    使用Python Lua和Ruby语言进行游戏编程

    "Premier.Press.Game.Programming.with.Python.Lua.and.Ruby.ebook-LiB.chm"很可能是一本关于使用这三种语言进行游戏编程的电子书,它可能会详细介绍如何利用这些语言来开发游戏,涵盖从基础概念到高级技巧的各种...

    21个你应该知道的Ruby编程技巧

    以下是从标题、描述和部分内容中提炼的21个你应该知道的Ruby编程技巧: 1. **快速获取正则表达式的匹配值** 通过使用`String#[]`方法,你可以直接匹配正则表达式,避免了`match`方法可能抛出的异常。例如,`email...

    ruby官方chm文档

    理解如何使用`eval`、`class_eval`和`instance_eval`,以及如何利用`send`和`method_missing`进行消息传递,是提升Ruby编程技巧的关键。 《ruby23.chm》文档可能是整个Ruby语言的综合指南,可能包含前面几个文档的...

    ruby 技巧文档

    在Ruby编程语言中,"ruby 技巧"涵盖了广泛的领域,包括但不限于面向对象编程、类与对象、模块、方法、变量、控制结构、异常处理、文件操作、网络编程等。以下我们将重点讨论Ruby中用于发送电子邮件的相关技巧,这...

    Ruby 教程 The Book of Ruby

    - Ruby版本管理工具如RVM和rbenv的使用 - 开发环境的搭建与配置 3. **基础知识** - 数据类型(数字、字符串、数组等) - 变量与常量 - 控制结构(条件语句、循环语句) 4. **面向对象编程** - 类与对象的...

    ruby中英文api

    "The Ruby Way.chm"则可能是《The Ruby Way》一书的电子版,这是一本深入介绍Ruby编程实践的书籍,它不仅讲解了Ruby的基本语法,还分享了编写高效、简洁Ruby代码的技巧。书中可能包含了大量的示例代码和实践案例,...

    ruby-debug命令详解

    本文将详细介绍`ruby-debug`的使用方法和核心特性。 ### 一、安装`ruby-debug` 首先,为了使用`ruby-debug`,你需要确保你的系统已经安装了`ruby`, `rubygems`和`debugger` gem。你可以通过以下命令来安装: ```...

    ruby完全安装过程

    - `Ruby on Rails实践.pdf`:这本书可能是关于使用Rails进行实际开发的指南,涵盖从基础概念到高级技巧的全方位内容,帮助你从实践中学习。 7. **实践项目**:理论学习后,动手实践是巩固知识的关键。尝试创建一个...

    Ruby教程.chm和Ruby程序设计.doc

    这份“Ruby教程.chm”和“Ruby程序设计.doc”提供了学习Ruby的宝贵资源,旨在帮助初学者快速掌握Ruby的核心概念和编程技巧。 首先,让我们深入了解一下Ruby教程.chm。CHM是微软编写的帮助文档格式,通常包含索引、...

    Programming Ruby.pdf

    书中通过大量的实例和详细的解释,帮助读者掌握Ruby的核心概念和编程技巧。此外,该书还涵盖了Ruby生态系统中的各种工具和库,如Rake、RSpec等,这些工具极大地丰富了Ruby的开发环境,使得Ruby成为了一种既强大又...

    eloquent ruby

    - 调试技巧,包括使用p方法打印变量值、调试工具如byebug等。 7. **Ruby生态系统** - 宝石(Gems)管理:Bundler用于项目依赖管理。 - 社区资源和最佳实践。 - 部署和运维相关的工具与服务。 8. **面向Web开发**...

    ruby脚本交互.rar

    在"ruby脚本交互.rar"这个压缩包中,包含的可能是一份使用Ruby语言进行脚本交互的易语言源码。易语言是中国自主研发的一种简单易学的编程语言,它允许程序员用自然语言般的语法编写程序。下面我们将深入探讨Ruby脚本...

    Best of Ruby Quiz

    《Best of Ruby Quiz》通过一系列精心设计的问题和解答,帮助读者巩固和拓展对Ruby的理解,提高编程技巧和解决问题的能力。无论是初学者还是经验丰富的开发者,都能从中受益匪浅。阅读这本书,不仅能够提升编程能力...

    Ruby基础教程(第5版)1

    此外,Ruby的面向对象特性是其一大亮点,书中详细介绍了如何创建和使用类,以及如何利用Ruby的鸭子类型实现灵活的编程。 高级主题,如正则表达式,也在书中有所涉及,这些内容对提升开发者解决复杂问题的能力至关...

    ruby 经典教程从新手到专家

    - **Web开发**:使用Ruby on Rails框架构建动态网站。 - **系统管理脚本**:编写用于系统管理和自动化任务的脚本。 - **游戏开发**:使用Ruby进行基本的游戏开发。 ### 学习Ruby的理由 - **简洁易学**:Ruby的语法...

Global site tag (gtag.js) - Google Analytics