Array from a custom class in ruby - ruby

I have a custom class,
class Result
end
and i want to create an array of objects from it, but i cannot figure out how to do it? Because results = Array.new creates a new array, but i cannot find where to pass the class?

Presuming I understand the question correctly, the answer is: you don't. Ruby is dynamically typed, so the array is just an array and doesn't need to know that it's going to contain objects of class Result. You can put anything into the array.

Are you looking for something like this,
class Result
end
result = Array.new(5) { Result.new }
#=> [#<Result>, #<Result>, #<Result>, #<Result>, #<Result>]
Obviously you can pass any number you want.

results = Array.new creates an empty array (as would results = [], which is more succinct). To create an array containing result objects, either create an empty array and add elements to it, or use an array literal like [element1, element2, ...].
For example results = [Result.new, Result.new, Result.new] would create an array containing three Result objects.

You should just be able to create as many Result objects as you need and append them to the array. The array can hold objects of any type.
result1 = Result.new
result2 = Result.new
result3 = Result.new
results = Array.new
results << result1
results << result2
results << result3
Your results array now has 3 Result objects in it.

Related

Map array values to the ruby hash key

here i have the sample code , mapping array to hash and appending hash to array but expected output is missing the array value
data = {"a"=>5,"b"=>["e","f"]}
data1 = [44,55]
s = []
data1.each_with_index do |i,index|
a = data1[index]
data["b"] = i
s << data
end
p s
output:
[{"a"=>5, "b"=>55}, {"a"=>5, "b"=>55}]
Expected output:
[{"a"=>5, "b"=>44}, {"a"=>5, "b"=>55}]
Your main problem is that you are putting the same object reference into each of your array elements. Think of it as putting two keys to the same locker in two different places. If you change the stuff in the locker, both keys will open it, and they will both see the same stuff. So, when you change the value of 'b', you change it for the object in both array elements, because they're the same object.
The solution is to start your block by creating a copy of the data object, changing its 'b' value, and putting the result into the resulting array.
I've also changed your each_with_index to map, because map is best to use when you are transforming the values in the array. Also, you don't need to have the index available in your block; you're just running through the array elements without caring which element you're working with while you're working with it.
data = {"a"=>5,"b"=>["e","f"]}
data1 = [44,55]
s = []
data1.map do |num|
the_copy = data.clone
the_copy['b'] = num
s << the_copy
end
p s

Iterating Over Multidimensional Arrays in Ruby

I'm going over iteration within multidimensional arrays in Ruby on Codecademy and came across a question I can't seem to find the answer to. So, in their example, they show that a multidimensional array can be iterated using the following code:
things = [[1,2,3], ["red", "blue"]]
things.each do |sub_array|
sub_array.each do |item|
puts item
end
end
This prints out the values of both sub_arrays. However, if I only want to display one sub_array, how would I go about that? I have tried the following code but I'm getting an undefined method `each' for 2:Fixnum error.
things = [[1,2,3], ["red", "blue"]]
things.each do |numbers, colors|
colors.each { |item| puts item }
end
So, I guess my question is why my code is not functioning correctly and how I would go about printing out only the array at index 1?
Your block parameters deconstruct the array as follows:
The enumerator generated by :each yields each element of the outer array in sequence, and then applies the pattern matching based on the structure of the block parameters. So in the first iteration, you have [1,2,3] yielded to the block, which is then mapped to numbers = 1 and colors = 2. 3 is ignored because it doesn't fit the pattern.
If you only want to display one sub-array, you don't need iterate over the whole array- just grab the required element by the index (if you know what the index is):
things[1].each {|color| ... }
Or, you can assign it to a variable in a similar way. As long as you know the colors will always be in the second position, you can do this:
_, colors = *things
colors.each {|color| ... }

Subtraction of two arrays with incremental indexes of the other array to a maximum limit

I have lots of math to do on lots of data but it's all based on a few base templates. So instead of say, when doing math between 2 arrays I do this:
results = [a[0]-b[1],a[1]-b[2],a[2]-b[3]]
I want to instead just put the base template: a[0]-b[1] and make it automatically fill say 50 places in the results array. So I don't always have to manually type it.
What would be the ways to do that? And would a good way be to create 1 method that does this automatically. And I just tell it the math and it fills out an array?
I have no clue, I'm really new to programming.
a = [2,3,4]
b = [1,2,3,4]
results = a.zip(b.drop(1)).take(50).map { |v,w| v - w }
Custom
a = [2,3,4..............,1000]
b = [1,2,3,4,.............900]
class Array
def self.calculate_difference(arr1,arr2,limit)
begin
result ||= Array.new
limit.send(:times) {|index| result << arr1[index]-arr2[index+=1]}
result
rescue
raise "Index/Limit Error"
end
end
end
Call by:
Array.calculate_difference(a,b,50)

Delete one of many from Array

I have an Array that contains some elements multiple times. Now I want to create a new Array with one of those elements deleted.
Example:
a = [1,1,1,2]
delete_index = a.find_index(1)
result = a.clone
result.delete_at(delete_index)
# result is now [1,1,2]
This code looks really ugly for such an easy task. I had a look at the methods that Array provides, but couldn't find a better way of doing this.
a.delete_at(a.index(1) || a.length)
a.length handles the case where your element isn't found; because it's out of range, nothing will be deleted and your return value wil be nil.
If part of your question was to do this to a copy of the array, just call it on a clone:
a2 = a.clone ; a2.delete_at(...)
If you want to do this for each duplicated element, you can chain it to a block that selects the duplicated elements:
a.select { |e| array.count(e) > 1 }.each { |dup| a.delete_at a.index(dup) }
You could monkey patch Array:
class Array
def delete_first_occurrence(o)
delete_at(find_index(o) || length)
self
end
end
a = [1,1,1,2]
result = a.clone.delete_first_occurrence(1)
=> [1, 1, 2]
I can't quite tell, but it sounds like you're just trying to remove duplicates from the array. If that's the case, it's as easy as array.uniq, which will return a new array with all duplicates removed. If you'd like to modify the original array in place, you can use array.uniq! instead.
If that's not what you're trying to accomplish, please update your question with some example input and output of what you're trying to accomplish.

basic question ruby store value from table to array

I read that initialitation of array in ruby is like
myarray = [apple.txt, house.txt]
How can I store the value of a table in an array
if !haus.blank?
#from below, I will get a list of haus.name that I need to store in an array
haus.each do |f|
hausname = haus.name
end
end
i need to store each of the haus.name that I get from iterating in haus table to
myarray=[listofhaus.name]
How can I do this in ruby?
Thank you for your help
You can get all the array of names using the map
myarray = haus.map {|f| f.name} or
myarray = haus.map(&:name)
myarray = haus.collect(&:name)
I take i you're on Rails. Since your each iteration doesn't really make sense, here's a generic example:
Haus.all.map {|h| h.name }
This get's all objects of model Hause and maps the name attribute of each into an array.

Resources