gpt4 book ai didi

ruby-on-rails - 如果值为真,如何返回哈希键?

转载 作者:太空宇宙 更新时间:2023-11-03 17:04:32 28 4
gpt4 key购买 nike

给定一个哈希值

  PLATFORMS = {
:mac => /(mac)|(macintosh)/i,
:win => /(win)|(windows)/i,
:ipad => /(ipad)/i,
:iphone => /(iphone)/i,
:ipod => /(ipod)|(ipod touch)/i
}

我有兴趣返回散列键,其中值(在本例中是正则表达式)返回 true。

因此,如果我得到一个字符串 "windows",我应该返回 key :win

到目前为止我的尝试是:

current_platform = BrowserExperience::ExperienceKeeper::PLATFORMS.detect do |platform, regex|        
regex.match(user_agent_obj.platform)
end[0]

它返回 [:win,/(win)|(windows)/i]

但是,它只返回一个数组,其中索引 0 返回我想要的键值。有没有更简单的方法?

最佳答案

为什么不使用 case 语句?这是一种更常见的方法:

strings = [
'this is a Windows box',
'Welcome to Macintosh',
'My music is on an iPod',
'My photos are on an iPod Touch',
'I read books on an iPad'
]

strings.each do |str|
os = case str
when /\b(?:mac|macintosh)\b/i
:mac
when /\b(?:win|windows)\b/i
:win
when /\b(?:ipad)\b/i
:ipad
when /\b(?:iphone)\b/i
:iphone
when /\b(?:ipod|ipod\ touch)\b/i
:ipod
end

os # => :win, :mac, :ipod, :ipod, :ipad

end

也可以这样做:

PLATFORMS = {
mac: /\b(?:mac|macintosh)\b/i,
win: /\b(?:win|windows)\b/i,
ipad: /\b(?:ipad)\b/i,
iphone: /\b(?:iphone)\b/i,
ipod: /\b(?:ipod|ipod\ touch)\b/i
}

strings.each do |str|

key = nil

PLATFORMS.each_pair do |k, v|
if str =~ v
key = k
break
end
end

key # => :win, :mac, :ipod, :ipod, :ipad

end

或者最好的:

strings.each do |str|

PLATFORMS.find { |k, v| str =~ v }.first # => :win, :mac, :ipod, :ipod, :ipad

end

如果您使用散列和正则表达式,请使用更简洁的模式。 \b 是一个单词边界,它是我们告诉 Regexp 引擎是匹配子串还是整个单词的方式:

'machine'[/(?:mac|macintosh)/i]     # => "mac"

对比:

'machine'[/\b(?:mac|macintosh)\b/i] # => nil

还有一点:

'mac'[/\b(?:mac|macintosh)\b/i]           # => "mac"
'macintosh'[/\b(?:mac|macintosh)\b/i] # => "macintosh"
'win'[/\b(?:win|windows)\b/i] # => "win"
'windows'[/\b(?:win|windows)\b/i] # => "windows"
'ipad'[/\b(?:ipad)\b/i] # => "ipad"
'iphone'[/\b(?:iphone)\b/i] # => "iphone"
'ipod touch'[/\b(?:ipod|ipod\ touch)\b/i] # => "ipod"

我可能会做这样的事情来定义散列:

require 'regexp_trie'

PLATFORMS = {
mac: ['mac', 'macintosh'],
win: ['win', 'windows'],
ipad: ['ipad'],
iphone: ['iphone'],
ipod: ['ipod', 'ipod touch']
}

然后,我会将模式转换为更高效的模式:

PLATFORMS_RE = {}
PLATFORMS.each_pair do |k, v|
PLATFORMS_RE[k] = /\b(?:#{RegexpTrie.union(v).source})\b/i
end

结果是:

PLATFORMS_RE
# => {:mac=>/\b(?:mac(?:intosh)?)\b/i,
# :win=>/\b(?:win(?:dows)?)\b/i,
# :ipad=>/\b(?:ipad)\b/i,
# :iphone=>/\b(?:iphone)\b/i,
# :ipod=>/\b(?:ipod(?:\ touch)?)\b/i}

然后像以前一样工作:

strings.each do |str|

PLATFORMS_RE.find { |k, v| str =~ v }.first # => :win, :mac, :ipod, :ipod, :ipad

end

关于ruby-on-rails - 如果值为真,如何返回哈希键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44465125/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com