How to push to an array without explicit declaration? - ruby

I have an array of Rails app User objects (users) and I am gathering email entries from these objects in a new array. I am tired of doing:
emails = []
users.each {|user| emails << user.email}
Is there a way to declare and use an array in a single go in an enumerator block like that?

Use #collect method
users.collect {|user| user.email }
# in short
users.collect(&:email)
collect emails will be nice to read rather than map emails, so I will use #collect. But both the methods are synonym of each other.

There is #each_with_object method.
users.each_with_object( [] ) {|user, emails| emails << user.email}
Not really a good example, collect works much better here, since you need an array. However, if you ever happen to use a different container, not an array (maybe some custom class), this might be handy.
And I also have to note that it looks much like ActiveRecord usage, since it's about Rails. So you might find #pluck useful:
I can't provide an equal piece of code here, because I have no idea what do you have in users. But here's a similar snippet:
User.all.pluck(:email)

Related

how to check for an attribute in an array in ruby-on-rails

I need to find whether a specific attribute is present or not with where statement that takes an array in ruby.
I tried like the below.
User.where(id: [1,2,3]).include?('address')
User.where(id: [1,2,3]) would return a relation (which behaves pretty much as an array, but that's another story). It means, that is consists of objects - instances of User class.
You check if this collection includes string ('address'). It is not, as you may guess by now.
If you need to map all users by address, you can use pluck:
User.where(id: [1,2,3]).pluck(:address)
You could use: User.where(id: [1,2,3]).map(&:address) which will return an array containing the addresses.
And you can use User.where(id: [1,2,3]).map(&:address).map(&:present?) if you want an array with true or false value

DataMapper use only certain columns

I have a code section like the following:
users = User.all(:fname => "Paul")
This of course results in getting all users called "Paul". Now I only need some of the columns available for each user which leads to replacing the above line by something like this:
users = User.all(:name => "Paul", :fields => [:id, :fname, :lname, :email])
Until now everything works as expected. Unfortunately now I want to work with users but as soon as I use something like users.to_json, also the other columns available will be lazy-loaded even due the fact, that I don't need those. What's the correct or at least a good way to end up with users only containing the attributes for each user that I need?
An intermediate object like suggested in How to stop DataMapper from double query when limiting columns/fields? is not a very good option as I have a lot of places where would need to define at least twice which fields I need and also I would loose the speed improvement gained by loading only the needed data from the DB. In addition such an intermediate object also seems to be quite ugly to build when having multiple rows of the DB selected (=> multiple objects in a collection) instead of just one.
If you usually works with the collection using json I suggest overriding the as_json method in your model:
def as_json(options = nil)
# this example ignores the user's options
super({:only => [:fname]}.merge(options || {}))
end
You are able to find more detailed explanation here http://robots.thoughtbot.com/better-serialization-less-as-json

How can I efficiently pull specific information from JSON

I currently have a public Google calendar that I am successfully pulling JSON data down using Google's API.
I am using HTTParty to convert the JSON to a ruby object.
response = HTTParty.get('http://www.google.com/calendar/feeds/colorado.edu_mdpltf14q21hhg50qb3e139fjg#group.calendar.google.com/public/full?alt=json&orderby=starttime&max-results=15&singleevents=true&sortorder=ascending&futureevents=true')
I want to retrieve many titles, event names, start times, end times ect. I can get these with commands like
response["feed"]["title"["$t"]
for the calendar's title, and
response["feed"]["entry"][0]["title"]["$t"]
for the event's title.
My question is two-fold. One, Is there a simpler way to pull this data? Two, how can I go about pulling multiple events information? I tried:
response.each do |x| response["feed"]["title"]["$t"]
but that spits out a no implicit conversion of string into integer error.
Based on your examples this should do it
response["feed"]["entry"].map {|entry| entry["title"]["$t"] }
response['feed']['entry'] is a simple array of hashes. It is probably best to extract that array to a temporary variable with
entries = response['feed']['entry']
thereafter your code it depends entirely on what you need to achieve. For instance, using the URL that you have provided
puts entries.length
shows
2
And
entries.each do |entry|
puts entry['title']['$t']
end
gives
NEW EVENT
Future EVENT
If we can help you to achieve something specific then please alter your answer or ask for clarification in a comment.

How to get the collection based upon the wildchar redis key using redis-rb gem?

The redis objects created using the redis-rb gem.
$redis = Redis.new
$redis.sadd("work:the-first-task", 1)
$redis.sadd("work:another-task", 2)
$redis.sadd("work:yet-another-task", 3)
Is there any method to get the collection that has "work:*" keys?
Actually, if you just want to build a collection on Redis, you only need one key.
The example you provided builds 3 distinct collections, each of them with a single item. This is probably not that you wanted to do. The example could be rewritten as:
$redis = Redis.new
$redis.sadd("work","the-first-task|1")
$redis.sadd("work", "another-task|2")
$redis.sadd("work", "yet-another-task|3")
To retrieve all the items of this collection, use the following code:
x = $redis.smembers("work")
If you need to keep track of the order of the items in your collection, it would be better to use a list instead of a set.
In any case, usage of the KEYS command should be restricted to tooling/debug code only. It is not meant to be used in a real application because of its linear complexity.
If you really need to build several collections, and retrieve items from all these collections, the best way is probably to introduce a new "catalog" collection to keep track of the keys corresponding to these collections.
For instance:
$redis = Redis.new
$redis.sadd("catalog:work", "work:the-first-task" )
$redis.sadd("catalog:work", "work:another-task" )
$redis.sadd("work:the-first-task", 1)
$redis.sadd("work:the-first-task", 2)
$redis.sadd("work:another-task", 3)
$redis.sadd("work:another-task", 4)
To efficiently retrieve all the items:
keys = $redis.smembers("catalog:work")
res = $redis.pipelined do
keys.each do |x|
$redis.smembers(x)
end
end
res.flatten!(1)
The idea is to perform a first query to get the content of catalog:work, and then iterate on the result using pipelining to fetch all the data. I'm not a Ruby user, so there is probably a more idiomatic way to implement it.
Another simpler option can be used if the number of collections you want to retrieve is limited, and if you do not care about the ownership of the items (in which set is stored each item)
keys = $redis.smembers("catalog:work")
res = $redis.sunion(*keys)
Here the SUNION command is used to build a set resulting of the union of all the sets you are interested in. It also filters out the duplicates in the result (this was not done in the previous example).
Well, I could get it by $redis.keys("work:*").

how to group objects in an array Ruby

I have an array of users who are managers.
However there are repeated Users.
I would like to group them so that there is only one instance of each User in the array.
What would be the best way to go about this?
#managers.sort_by{|obj| obj.id} # Just sorted the data but did not eliminate duplicats
#managers.group_by{|u|u.name} # just created a bunch of arrays for each name
Use the uniq method, which returns a new array with duplicates removed.
#managers.uniq
If by duplicate you mean the same object ID, then you can do the following:
#managers.uniq.group_by(&:name)
Filtering the array feels like fixing symptoms. Why does the array contain rubbish in the first place?
I would suggest adding a manager? method to your User model that returns true if the user is a manager. Then you could to something like
#managers = User.select &:manager?
and get an array that only contains managers.
you can also do
Manager.select('DISTINCT user_id')
to get a clean array in the first place, whith better performance.

Resources