Wednesday, September 19, 2012

[Rails] Re: mark multiple results

Thanks.. this is helpfull
Greetings

On Wednesday, September 19, 2012 6:09:48 PM UTC+2, Ruby-Forum.com User wrote:
class User
  attr_accessor :id, :name

  def initialize(id, name)
    @id = id
    @name = name
  end
end

charlie = User.new(9, 'Charlie')
fred = User.new(1, 'Fred')
sally = User.new(3, 'Sally')

@users = [
  fred,
  fred,
  fred,
  sally,
  charlie,
  sally
]

user_counts = Hash.new(0)

@users.each {|user| user_counts[user] += 1}
p user_counts
puts

--output:--
{#<User:0x00000100867be8 @id=1, @name="Fred">=>3,
#<User:0x00000100867b70 @id=3, @name="Sally">=>2,
#<User:0x00000100867d00 @id=9, @name="Charlie">=>1}

ordered_results = user_counts.sort_by{|user| -user_counts[user]}
p ordered_results
puts

--output:--
[[#<User:0x00000100867be8 @id=1, @name="Fred">, 3],
[#<User:0x00000100867b70 @id=3, @name="Sally">, 2],
[#<User:0x00000100867d00 @id=9, @name="Charlie">, 1]]


cutoff = 2
most_appearances = ordered_results.take_while {|user, count| count >=
cutoff}
p most_appearances
puts

--output:--
[[#<User:0x00000100867be8 @id=1, @name="Fred">, 3],
[#<User:0x00000100867b70 @id=3, @name="Sally">, 2]]


top_users = most_appearances.map {|user, count| user}
p top_users

--output:--
[#<User:0x00000100867be8 @id=1, @name="Fred">, #<User:0x00000100867b70
@id=3, @name="Sally">]

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/1u9hqi__OjMJ.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate