Ruby的下划线魔法

I discovered today that Ruby treats underscores a little bit differently when it comes to variable names.

Suppose, for the sake of argument, that we have a set of data that looks like this:

CODE:

people = {
  "Alice" => ["green", "alice@example.com"],
  "Bob"   => ["brown", "bob@example.com"]
}and we want to ignore eye colour and age and convert each element to a simple array containing name and email address. We might do this:

CODE:

people.map { |name, fields| [name, fields.last] }but it's not very clear what fields.last is. Ruby has some fairly powerful destructuring assignment, so we can reach inside the structure with parentheses to make things more explicit:

CODE:

people.map { |name, (eye_color, email)| [name, email] }
请使用浏览器的分享功能分享到微信等