新手问题 readable, _, _ = IO.select (sockets) 的语法怎么讲?

ane · May 12, 2014 · Last by ane replied at May 14, 2014 · 2747 hits

readable, _, _ = IO.select(sockets)为什么需要连个占位符?

并行赋值,下划线表示忽略

#1 楼 @saiga 意思是忽略 Array[1] 和 Array[2]?

额,Matlab 里有类似的语句。。。我估计是右边的函数返回三个值,只要第一个,第二三个不要了。。。。

IO.select(sockets) 返回一个长度为 3 的数组,这句会用并行赋值的语法赋值给左边三个值,可以不需要用到后两个,所以就用_

请问readable = IO.select(sockets).first是否也可以

#5 楼 @leozwa 看起来是可以的

This method will generate warnings that the family, port, and host variables are unused.

def get_ip(sock)
  family, port, host, address = sock.peeraddr
  address
end

Using underscores will stop the warnings, but lose the self-documenting nature of the code

def get_ip(sock)
  _, _, _, address = sock.peeraddr
  address
end

As of Ruby 2.0.0 we can get the best of both worlds by starting the variables with an _

def get_ip(sock)
  _family, _port, _host, address = sock.peeraddr
  address
end

#5 楼 @leozwa ruby 里这样写是可以的,所以我觉得 rails 也应该可以

@leozwa 那样不可以,如果返回的是个数组,那 readable 变量就会变成数组变量

函数返回好几个值只需要一部分,其他的就拿来占位咯。

#10 楼 @kevinclcn 他用了个 first。IO.select 返回的是个 array 或者 nil。所以我觉得 OK。等我明天试试

#11 楼 @teddy_1004 之前看 js 的时候,很多有这样的写法,所以感觉眼熟

#12 楼 @ane 返回正常没问题,如果是 nil 就不行了

#14 楼 @kevinclcn nil 也是可以赋值的啊

#15 楼 @ane nil 没有 first

#16 楼 @kevinclcn 有道理 没考虑到 nil 以为会返回 empty array

#16 楼 @kevinclcn 确实,你说的没错,nil 没有 first,

result = (array_or_nil || []).first

result = array_or_nil.to_a.first 😄

#19 楼 @tnt readable = IO.select(sockets).first unless IO.select(sockets)==nil

#19 楼 @tnt 有 array_or_nil 这样的方法吗?

#21 楼 @ane 不是,代指 IO.select(sockets) 这种可能返回 Array 也可能返回 nil 的变量。

#22 楼 @tnt 那你还是用我的方式吧,要不你还要重定义一个 function

#23 楼 @ane

不用定义函数,我指的

readable = (IO.select(sockets) || []).first

或者

readable = IO.select(sockets).to_a.first

其实不怕污染的话简单粗暴定义

def nil.first; nil end

就可以直接

readable = IO.select(sockets).first

#24 楼 @tnt 还是喜欢 readable = (IO.select(sockets) || []).first

You need to Sign in before reply, if you don't have an account, please Sign up first.