Hidden features of Ruby

2019-01-04 04:31发布

Continuing the "Hidden features of ..." meme, let's share the lesser-known but useful features of Ruby programming language.

Try to limit this discussion with core Ruby, without any Ruby on Rails stuff.

See also:

(Please, just one hidden feature per answer.)

Thank you

30条回答
孤傲高冷的网名
2楼-- · 2019-01-04 04:40

Class.new()

Create a new class at run time. The argument can be a class to derive from, and the block is the class body. You might also want to look at const_set/const_get/const_defined? to get your new class properly registered, so that inspect prints out a name instead of a number.

Not something you need every day, but quite handy when you do.

查看更多
何必那么认真
3楼-- · 2019-01-04 04:41

Auto-vivifying hashes in Ruby

def cnh # silly name "create nested hash"
  Hash.new {|h,k| h[k] = Hash.new(&h.default_proc)}
end
my_hash = cnh
my_hash[1][2][3] = 4
my_hash # => { 1 => { 2 => { 3 =>4 } } }

This can just be damn handy.

查看更多
你好瞎i
4楼-- · 2019-01-04 04:43

Hashes with default values! An array in this case.

parties = Hash.new {|hash, key| hash[key] = [] }
parties["Summer party"]
# => []

parties["Summer party"] << "Joe"
parties["Other party"] << "Jane"

Very useful in metaprogramming.

查看更多
放我归山
5楼-- · 2019-01-04 04:43

Boolean operators on non boolean values.

&& and ||

Both return the value of the last expression evaluated.

Which is why the ||= will update the variable with the value returned expression on the right side if the variable is undefined. This is not explicitly documented, but common knowledge.

However the &&= isn't quite so widely known about.

string &&= string + "suffix"

is equivalent to

if string
  string = string + "suffix"
end

It's very handy for destructive operations that should not proceed if the variable is undefined.

查看更多
放荡不羁爱自由
6楼-- · 2019-01-04 04:46

The Symbol#to_proc function that Rails provides is really cool.

Instead of

Employee.collect { |emp| emp.name }

You can write:

Employee.collect(&:name)
查看更多
做自己的国王
7楼-- · 2019-01-04 04:49

Another tiny feature - convert a Fixnum into any base up to 36:

>> 1234567890.to_s(2)
=> "1001001100101100000001011010010"

>> 1234567890.to_s(8)
=> "11145401322"

>> 1234567890.to_s(16)
=> "499602d2"

>> 1234567890.to_s(24)
=> "6b1230i"

>> 1234567890.to_s(36)
=> "kf12oi"

And as Huw Walters has commented, converting the other way is just as simple:

>> "kf12oi".to_i(36)
=> 1234567890
查看更多
登录 后发表回答