Ruby Arrays and Hashes

Came to know about these :

Inject method:

Say you have an array a1 = [1,2,3,4,5] and you want to sum up the elements, then do this –

a1.inject(0) {| sum_so_far, item | sum_so_far + item}

This iterates over all the five elements and returns 15.

To find the product:

a1.injetc(1) { | product, item| product * item}

Collect method:

An array, a = [1, 2, 3]

a.collect {|element| element * 2}

This iterates over [1, 2, 3] and doubles it up to give…(no prizes for guessing)

Partition Method:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

odd_and_even = numbers.partition {|number| number % 2 == 1}

Result = [[1, 3, 5, 7, 9], [2, 4, 6, 8]]

Map method:

array = %w{one two three four}

array.map {| word | word.capitalize}

Result = [“One”, “Two”, “Three”, “Four”]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s