group on hash

sselvamani22 Feb 12, 2016

'

def group_by_hash hash, value
  hash.group_by do |k,v| 
    v > value ? "Big" : "Small"
  end
end

marks = {"Chair" => 30, "Table" => 40, "Bed" => 60, "stool" => 20}
group_by_hash(marks, 30)

Generate Token

eltin182 Feb 12, 2016

For generate a token, make this:

def generate_token
self.token = SecureRandom.uuid
end

SecureRandom return a number random and the uuid make this number be unique. This a good idea for use in shopping cart, for example

Fetch with default value

suzuki Feb 4, 2016

You can specify default value as a fail-back if a hash doesn't have a given key.

{a: false}.fetch(:b, true) => true {a: false}.fetch(:a, true) => false

It is useful especially in the case where you want to set default value for a method.

def initialize(args) @foo = args.fetch(:foo, 1)...

Re: close but no bananna

WhyEee Nov 3, 2015 1 thank

Actually, @tarasevich is right on this. Let's have a look at your own example:

[["1","2"],["3","4"]].flat_map {|i| i[0] }     # => ["1", "3"]

[["1","2"],["3","4"]].map {|i| i[0] }.flatten  # => ["1", "3"]
[["1","2"],["3","4"]].flatten.map {|i| i[0] }  # => ["1", "2", "3", "4"]

You are...

close but no bananna

masukomi Nov 3, 2015

@tarasevich noted that

a.flat_map(&b) works exactly like a.map(&b).flatten!(1)

This is backwards because map and flatten are not always interchangeable in order. Mapping over the example array only gives you 2 items. This can result in significant differences depending on what you're d...