如何将map与to_s结合?

时间:2022-10-30 08:08:56

I am using Mongoid and retrieving a bunch of BSON::ObjectId instances. Ideally, I'd like to convert them to strings upon retrieval. What's the correct syntax? It can be done in two lines like this:

我正在使用Mongoid并检索一组BSON:::ObjectId实例。理想情况下,我希望在检索时将它们转换为字符串。正确的语法是什么?它可以用两行来完成:

foo = Bar.where(:some_id => N).map(&:another_id)
ids_as_strings = foo.map(&:to_s)

What's the proper Ruby way to chain to_s after the map invocation above?

在上面的映射调用之后,链接to_s的正确Ruby方法是什么?

2 个解决方案

#1


8  

This works fine, but don't do it!

这个方法很有效,但是不要这么做!

ids_as_string = Bar.where(:some_id => N).map(&:another_id).map(&:to_s)

It looks cool for sure, but think about it, you are doing two maps. A map is for looping over an array, or something else, and will operate in each position, retrieving a new array, or something else, with the results.

它看起来很酷,但是想想看,你在做两张地图。映射用于在数组或其他东西上循环,并将在每个位置上操作,检索新的数组或其他结果。

So why do two loops if you want to do two operations?

如果你想做两个操作,为什么要做两个循环呢?

ids_as_string = Bar.where(:some_id => N).map {|v| v.another_id.to_s}

This should be the way to go in this situation, and actually looks nicer.

在这种情况下,这应该是可行的,而且看起来更漂亮。

#2


1  

You can just chain it directly:

你可以直接把它链起来:

ids_as_string = Bar.where(:some_id => N).map(&:another_id).map(&:to_s)

I tried this out with a model and I got what you expected, something like:

我试用了一个模型,我得到了你想要的结果,大概是:

["1", "2", ...]

#1


8  

This works fine, but don't do it!

这个方法很有效,但是不要这么做!

ids_as_string = Bar.where(:some_id => N).map(&:another_id).map(&:to_s)

It looks cool for sure, but think about it, you are doing two maps. A map is for looping over an array, or something else, and will operate in each position, retrieving a new array, or something else, with the results.

它看起来很酷,但是想想看,你在做两张地图。映射用于在数组或其他东西上循环,并将在每个位置上操作,检索新的数组或其他结果。

So why do two loops if you want to do two operations?

如果你想做两个操作,为什么要做两个循环呢?

ids_as_string = Bar.where(:some_id => N).map {|v| v.another_id.to_s}

This should be the way to go in this situation, and actually looks nicer.

在这种情况下,这应该是可行的,而且看起来更漂亮。

#2


1  

You can just chain it directly:

你可以直接把它链起来:

ids_as_string = Bar.where(:some_id => N).map(&:another_id).map(&:to_s)

I tried this out with a model and I got what you expected, something like:

我试用了一个模型,我得到了你想要的结果,大概是:

["1", "2", ...]