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:
"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:
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] }来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/301743/viewspace-745165/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/301743/viewspace-745165/