[英]Find value in an array of hashes
taglist = [{:name=>"Daniel_Xu_Forever", :tag=>["helo", "world"]},
{:name=>"kcuf", :tag=>["hhe"]},
{:name=>"fine", :tag=>[]},
{:name=>"how hare you", :tag=>[]},
{:name=>"heki", :tag=>["1", "2", "3"]},
{:name=>"railsgirls", :tag=>[]},
{:name=>"_byoy", :tag=>[]},
{:name=>"ajha", :tag=>[]},
{:name=>"nimei", :tag=>[]}]
How to get specified name's tag from taglist 如何从标签列表中获取指定名称的标签
For example , I want to extract user "fine"
's tag? 例如,我要提取用户
"fine"
的标签?
Could this be achieved without do
iterator? 没有能实现这一目标
do
迭代器?
This will return the contents of the :tag
key for any users name which == 'fine'
这将为
== 'fine'
任何用户名返回:tag
键的内容。
taglist.select { |x| x[:name] == 'fine' }.map { |u| u[:tag] }
First you select out only the users you are interested with .select
. 首先,您只选择
.select
感兴趣的用户。
And then use .map
to collect an array of only what you want. 然后使用
.map
收集仅所需数组。
In this case the end result will be: []
在这种情况下,最终结果将是:
[]
Is do
really an iterator? 是
do
一个真正的迭代器?
taglist.find{|tl| tl[:name] == 'fine'}[:tag]
Just to be silly how about: 只是愚蠢的如何:
eval taglist.to_s[/:name=>"fine", :tag=>(.*?)}/, 1]
#=> []
No, it cannot be done without a loop. 不,没有循环就无法完成。
And even if you find a solution where your code avoids a loop, for sure the library function that you're calling will include a loop. 即使找到了避免代码循环的解决方案,也要确保所调用的库函数将包含循环。 Finding an element in an array requires a loop.
在数组中查找元素需要循环。 Period.
期。
For example, take this (contrived) example 例如,以这个(人为)示例为例
pattern = "fine"
def pattern.===(h); self == h[:name]; end
taglist.grep(pattern)
which does not seem to use a loop, but calls grep
which is implemented using a loop. 似乎没有使用循环,而是调用了使用循环实现的
grep
。
Or another, equally contrived, example 或另一个同样人为设计的例子
class Hash; def method_missing(sym); self[sym]; end; end
taglist.group_by(&:name)["fine"]
which again does seem to call group_by
without a loop, but actually it does. 它似乎确实没有循环地调用
group_by
,但实际上确实如此。
So the answer is, no. 所以答案是,不。
So my first answer missed the no do
rule. 所以我的第一个答案错过了“
do
规则。 Here is an answer that doesn't use a do
block. 这是一个不使用
do
块的答案。
i=0
begin
if taglist[i][:name] == 'fine'
tag = taglist[i][:tag]
break
end
i+=1
end while i < taglist.length - 0
Technically I think this is still using a block. 从技术上讲,我认为这仍在使用一个块。 But probably satisfies the restriction.
但是可能满足该限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.