How to Return a Part of an Array in Ruby

How to return a part of an array in Ruby?

Yes, Ruby has very similar array-slicing syntax to Python. Here is the ri documentation for the array index method:

--------------------------------------------------------------- Array#[]
array[index] -> obj or nil
array[start, length] -> an_array or nil
array[range] -> an_array or nil
array.slice(index) -> obj or nil
array.slice(start, length) -> an_array or nil
array.slice(range) -> an_array or nil
------------------------------------------------------------------------
Element Reference---Returns the element at index, or returns a
subarray starting at start and continuing for length elements, or
returns a subarray specified by range. Negative indices count
backward from the end of the array (-1 is the last element).
Returns nil if the index (or starting index) are out of range.

a = [ "a", "b", "c", "d", "e" ]
a[2] + a[0] + a[1] #=> "cab"
a[6] #=> nil
a[1, 2] #=> [ "b", "c" ]
a[1..3] #=> [ "b", "c", "d" ]
a[4..7] #=> [ "e" ]
a[6..10] #=> nil
a[-3, 3] #=> [ "c", "d", "e" ]
# special cases
a[5] #=> nil
a[6, 1] #=> nil
a[5, 1] #=> []
a[5..10] #=> []

returning an array that contains an array and hash in ruby method?

Sure, that's perfectly possible and works exactly as in your example.

Return only the first and last items of an array in Ruby

You can use the values_at() method to get the first and last elements in an array like this:

def first_and_last(input_array)
input_array.values_at(0,-1)
end

Depending on what behavior you're looking for, it might not work on arrays with 1 or 0 elements. You can read more about the method here.

How return all elements array in Rails?

First, I'd write the controller more like this (untested) code:

def grafico_gantt 
@mapa = {}
@mapa[:tasks] = @projeto.atividades.map { |a|
{
id: a.id,
descricao: a.descricao,
status: a.status,
data_inicial: a.data_inicial.to_datetime.to_i * 1000,
tempo_gasto: a.tempo_gasto.to_i,
data_final: a.data_final.to_datetime.to_i * 1000
}
}
end

To access all the descricao elements of the returned array, use a map or collect to transform the array into just the parts you want:

@mapa[:tasks].collect { |e| e[:descricao] }

map and collect are synonymous. Though they are aliased, sometimes it makes more sense syntactically to use collect, and sometimes map makes more sense.

In the rewrite of the code above, it's a little confusing why you create a hash of hashes. A single element hash of hashes is a bit... confusing... inelegant, but maybe you're not showing us everything.

If nothing else is added to the hash, I'd recommend simplifying it to:

def grafico_gantt 
@mapa = @projeto.atividades.map { |a|
{
id: a.id,
descricao: a.descricao,
status: a.status,
data_inicial: a.data_inicial.to_datetime.to_i * 1000,
tempo_gasto: a.tempo_gasto.to_i,
data_final: a.data_final.to_datetime.to_i * 1000
}
}
end

Which will return an array of hashes and simplify your accesses into it by removing the need to find the [:tasks] element:

@mapa.collect { |e| e[:descricao] }

Ruby - How to write a method that returns an array of strings?

You are trying to write a function that should work on a single array at a time I think. Also, you are taking in an array, and retaining only those elements that satisfy your conditions: at least 5 characters long, and ends with y. This is a filtering operation. Read about the methods available for ruby's Array class here

def phrases(array)
...
filtered_array
end

Now the condition you are using is this arr1.length > 5 && arr1.length == "y".
The first half should check if the string length is greater than 5, not the array length itself. The second half is an indexing operation, and your code for that is incorrect. basically you are checking if the last character in the string is y.

Usually strings are indexed in this manner: string[index]. In your case you can use string[-1]=='y' or string[string.length - 1]=='y'. This because arrays and strings are zero indexed in ruby. The first element has index of 0, the second has an index of 1, and the last one, therefore, will have an index of length-1. If you use negative indexes then the array is indexed from the end, so string[-1] is a quick way to get to the last element.

Considering this, the function will take the following structure:

def phrases(array)
filtered_array = [] # an empty array
loop through the input array
for each element check for the condition element.length > 5 && element[-1]=='y'
if true: push the element into the filtered_array
once the loop is done, return the filtered array
end

Read about ruby arrays, the methods push, filter and select in the above linked documentation to get a better idea. I'd also recommend the codeacademy ruby tutorial.

Edit: Both halves of the condition are incorrect. I had overlooked a mistake in my earlier answer. arr1.length refers to the length of the array. You want to check the length of each string in the array. So in your for loop you should check the length of the loop variable, if that is greater than 5.

Ruby find and return objects in an array based on an attribute

array_of_objects.select { |favor| favor.completed == false }

Will return all the objects that's completed is false.

You can also use find_all instead of select.

Returning array from method in model in Ruby on Rails 3

Well, if calculate_royalty just returns a number, then in your loop you are not assigning it to anything, it just returns and disappears. Try pushing each royalty into an array and summing them at the end like so:

def total_author_royalties
royalties = []
products.each do |p|
royalties << calculate_royalty(p.id)
end
royalties.sum
end

or a more concise version:

def total_author_royalties
products.map{|p| calculate_royalty(p.id)}.sum
end

Ruby - print first part of string in element of array

So close:

puts "exercise #4 - print only first"
full_names = ["Alice Smith", "Bob Evans", "Roy Rogers"]
full_names.each do |name|
puts name.split.first
end


Related Topics



Leave a reply



Submit