- 浏览: 2075712 次
- 性别:
- 来自: NYC
文章分类
- 全部博客 (628)
- Linux (53)
- RubyOnRails (294)
- HTML (8)
- 手册指南 (5)
- Mysql (14)
- PHP (3)
- Rails 汇总 (13)
- 读书 (22)
- plugin 插件介绍与应用 (12)
- Flex (2)
- Ruby技巧 (7)
- Gem包介绍 (1)
- javascript Jquery ext prototype (21)
- IT生活 (6)
- 小工具 (4)
- PHP 部署 drupal (1)
- javascript Jquery sort plugin 插件 (2)
- iphone siri ios (1)
- Ruby On Rails (106)
- 编程概念 (1)
- Unit Test (4)
- Ruby 1.9 (24)
- rake (1)
- Postgresql (6)
- ruby (5)
- respond_to? (1)
- method_missing (1)
- git (8)
- Rspec (1)
- ios (1)
- jquery (1)
- Sinatra (1)
最新评论
-
dadadada2x:
user模型里加上 protected def email ...
流行的权限管理 gem devise的定制 -
Sev7en_jun:
shrekting 写道var pattern = /^(0| ...
强悍的ip格式 正则表达式验证 -
jiasanshou:
好文章!!!
RPM包rpmbuild SPEC文件深度说明 -
寻得乐中乐:
link_to其实就是个a标签,使用css控制,添加一个参数: ...
Rails在link_to中加参数 -
aiafei0001:
完全看不懂,不知所然.能表达清楚一点?
"$ is not defined" 的问题怎么办
翻出来一篇很老的东西,有些已经不用了,总之,抄回来,看看吧
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:
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:
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:
It's not well known, however, that when given a string as an argument Array#* does a join!
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:
4 - Interpolate text quickly
The formatting interpolation technique from #3 comes out again, this time to insert a string inside another:
You can use an array of elements to substitute in too:
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:
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:
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!):
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:
# 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:
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:
It can come in particularly useful for slurping method arguments that have been bundled into an array with *:
If you want to get really smart (although this is more 'clever' than truly wise):
12 - Use ranges instead of complex comparisons for numbers
No more if x > 1000 && x < 2000 nonsense. Instead:
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:
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):
16 - Fight redundancy with Ruby's "logic" features
I commonly see methods using this sort of pattern:
Perhaps we can use a ternary operator to improve things?
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!
Sometimes, though, you want to explicitly convert implicit true/false scenarios into explicit true/false results:
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
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'
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:
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:
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"
发表评论
-
Destroying a Postgres DB on Heroku
2013-04-24 10:58 935heroku pg:reset DATABASE -
VIM ctags setup ack
2012-04-17 22:13 3259reference ctags --extra=+f --e ... -
alias_method_chain方法在3.1以后的替代使用方式
2012-02-04 02:14 3295alias_method_chain() 是rails里的一个 ... -
一些快速解决的问题
2012-01-19 12:35 1472问题如下: 引用Could not open library ... -
API service 安全问题
2011-12-04 08:47 1386这是一个长期关注的课题 rest api Service的 ... -
Module方法调用好不好
2011-11-20 01:58 1349以前说,用module给class加singleton方法,和 ... -
一个ajax和rails交互的例子
2011-11-19 01:53 1908首先,这里用了一个,query信息解析的包,如下 https: ... -
Rails 返回hash给javascript
2011-11-19 01:43 2277这是一个特别的,不太正统的需求, 因为,大部分时候,ajax的 ... -
关于Rubymine
2011-11-18 23:21 2267开个帖子收集有关使用上的问题 前一段时间,看到半价就买了。想 ... -
ruby中和javascript中,动态方法的创建
2011-11-18 21:01 1241class Klass def hello(*args) ... -
textmate快捷键 汇总
2011-11-16 07:20 8147TextMate 列编辑模式 按住 Alt 键,用鼠标选择要 ... -
Ruby面试系列六,面试继续面试
2011-11-15 05:55 2025刚才受到打击了,充分报漏了自己基础不扎实,不肯向虎炮等兄弟学习 ... -
说说sharding
2011-11-13 00:53 1492这个东西一面试就有人 ... -
rails面试碎碎念
2011-11-12 23:51 1946面试继续面试 又有问ru ... -
最通常的git push reject 和non-fast forward是因为
2011-11-12 23:29 17216git push To git@github.com:use ... -
Rails 自身的many to many关系 self has_many
2011-11-12 01:43 2737简单点的 #注意外键在person上people: id ... -
Rails 3下的 in place editor edit in place
2011-11-12 01:20 946第一个版本 http://code.google.com/p ... -
Heroku 的诡异问题集合
2011-11-11 07:22 1697开个Post记录,在用heroku过程中的一些诡异问题和要注意 ... -
SCSS 和 SASS 和 HAML 和CoffeeScript
2011-11-07 07:52 12959Asset Pipeline 提供了内建 ... -
Invalid gemspec because of the date format in specification
2011-11-07 02:14 2122又是这个date format的错误。 上次出错忘了,记录下 ...
相关推荐
### Ruby的25个编程细节(技巧、实用代码段) #### 1. 使用 `try` 方法处理潜在的异常 在Ruby中,`try` 方法是一个非常有用的功能,它允许我们安全地访问对象的方法或属性,即使该对象为 `nil` 也不会抛出异常。...
一、Ruby技巧 1. 块和迭代器:Ruby中的块(blocks)和迭代器(iterators)是其强大之处。使用`each`、`map`等方法可以简洁地遍历集合。例如,`array.each { |item| puts item }`用于打印数组的所有元素。 2. 魔术...
### Ruby介绍、使用技巧和经典案例 #### 一、Ruby的基本概念 - **简洁灵活**:Ruby语言的设计理念强调简洁性和灵活性。它采用了一种直观且易于理解的语法,允许开发者使用较少的代码来实现复杂的功能。这种简洁性...
在 Ruby 中,程序员可以利用各种技巧来提高代码的可读性和效率。本文将深入探讨 Ruby 中的常值,包括数值、符号、字符串和正则表达式。 1. 数值 - 整数:Ruby 支持两种整数类型——Fixnum 和 Bignum。Fixnum 用于...
"Premier.Press.Game.Programming.with.Python.Lua.and.Ruby.ebook-LiB.chm"很可能是一本关于使用这三种语言进行游戏编程的电子书,它可能会详细介绍如何利用这些语言来开发游戏,涵盖从基础概念到高级技巧的各种...
以下是从标题、描述和部分内容中提炼的21个你应该知道的Ruby编程技巧: 1. **快速获取正则表达式的匹配值** 通过使用`String#[]`方法,你可以直接匹配正则表达式,避免了`match`方法可能抛出的异常。例如,`email...
理解如何使用`eval`、`class_eval`和`instance_eval`,以及如何利用`send`和`method_missing`进行消息传递,是提升Ruby编程技巧的关键。 《ruby23.chm》文档可能是整个Ruby语言的综合指南,可能包含前面几个文档的...
在Ruby编程语言中,"ruby 技巧"涵盖了广泛的领域,包括但不限于面向对象编程、类与对象、模块、方法、变量、控制结构、异常处理、文件操作、网络编程等。以下我们将重点讨论Ruby中用于发送电子邮件的相关技巧,这...
- Ruby版本管理工具如RVM和rbenv的使用 - 开发环境的搭建与配置 3. **基础知识** - 数据类型(数字、字符串、数组等) - 变量与常量 - 控制结构(条件语句、循环语句) 4. **面向对象编程** - 类与对象的...
"The Ruby Way.chm"则可能是《The Ruby Way》一书的电子版,这是一本深入介绍Ruby编程实践的书籍,它不仅讲解了Ruby的基本语法,还分享了编写高效、简洁Ruby代码的技巧。书中可能包含了大量的示例代码和实践案例,...
本文将详细介绍`ruby-debug`的使用方法和核心特性。 ### 一、安装`ruby-debug` 首先,为了使用`ruby-debug`,你需要确保你的系统已经安装了`ruby`, `rubygems`和`debugger` gem。你可以通过以下命令来安装: ```...
- `Ruby on Rails实践.pdf`:这本书可能是关于使用Rails进行实际开发的指南,涵盖从基础概念到高级技巧的全方位内容,帮助你从实践中学习。 7. **实践项目**:理论学习后,动手实践是巩固知识的关键。尝试创建一个...
3. **动态编程技巧**:通过具体示例展示如何利用Ruby的动态特性编写自修改程序,提升代码的灵活性和可扩展性。 4. **轻量级多任务**:介绍如何使用Fiber和Thread来实现并发编程,提高程序的执行效率。 5. **异常...
此外,Ruby的面向对象特性是其一大亮点,书中详细介绍了如何创建和使用类,以及如何利用Ruby的鸭子类型实现灵活的编程。 高级主题,如正则表达式,也在书中有所涉及,这些内容对提升开发者解决复杂问题的能力至关...
这份“Ruby教程.chm”和“Ruby程序设计.doc”提供了学习Ruby的宝贵资源,旨在帮助初学者快速掌握Ruby的核心概念和编程技巧。 首先,让我们深入了解一下Ruby教程.chm。CHM是微软编写的帮助文档格式,通常包含索引、...
书中通过大量的实例和详细的解释,帮助读者掌握Ruby的核心概念和编程技巧。此外,该书还涵盖了Ruby生态系统中的各种工具和库,如Rake、RSpec等,这些工具极大地丰富了Ruby的开发环境,使得Ruby成为了一种既强大又...
- 调试技巧,包括使用p方法打印变量值、调试工具如byebug等。 7. **Ruby生态系统** - 宝石(Gems)管理:Bundler用于项目依赖管理。 - 社区资源和最佳实践。 - 部署和运维相关的工具与服务。 8. **面向Web开发**...
在"ruby脚本交互.rar"这个压缩包中,包含的可能是一份使用Ruby语言进行脚本交互的易语言源码。易语言是中国自主研发的一种简单易学的编程语言,它允许程序员用自然语言般的语法编写程序。下面我们将深入探讨Ruby脚本...
《Best of Ruby Quiz》通过一系列精心设计的问题和解答,帮助读者巩固和拓展对Ruby的理解,提高编程技巧和解决问题的能力。无论是初学者还是经验丰富的开发者,都能从中受益匪浅。阅读这本书,不仅能够提升编程能力...