ITPub博客

首页 > Linux操作系统 > Linux操作系统 > Ruby的下划线魔法

Ruby的下划线魔法

原创 Linux操作系统 作者:jieforest 时间:2012-09-27 08:27:43 0 删除 编辑
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] }

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/301743/viewspace-745165/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-04-23

  • 博文量
    441
  • 访问量
    602351