开发者

searching an array using another array of values in ruby

开发者 https://www.devze.com 2023-02-01 16:32 出处:网络
So I have an array which shows which levels are allowed to do things. allowed = [\"user\", \"admin\"] There\'s another array that shows which groups a user belongs to.

So I have an array which shows which levels are allowed to do things.

allowed = ["user", "admin"]

There's another array that shows which groups a user belongs to.

groups = ["user", "crazy"]

What's th开发者_如何学Pythone best way to search the allowed array for ANY of the groups a user belongs to? I know it's easy but I'm drawing a real blank here...


Just &:

allowed & groups



Convert to a set and do an intersection.

require 'set'

allowed = ["user", "admin"]
has = ["user", "print"]
puts(allowed.to_set.intersection(has.to_set)) # prints #<Set: {"user"}>
0

精彩评论

暂无评论...
验证码 换一张
取 消