basic question ruby store value from table to array - ruby

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.

Related

Ruby pushing to a hash

I have a two part question and I apologize in advance if it is confusing at all. I'm trying to put user input into an empty hash. I know with an array you use the << to push the info to it. Is there a hash equivalent to this?
2nd part: Say I was just looping them the same question until a condition is met. The user input is going to be the value. Is there a way/method to make the key automatically change per the user input? So it would look something like:
{str1 => "example string", str2 => "example string2", str3 => "example string3"}
Or is there a way to have ruby assign a key on its own?
Sorry again if the second part is confusing. I know an array would be better but the little challenge I am working is asking for a hash.
Another way to add element to ruby hash store(key, value)
hash = {}
hash.store("first", 42)
hash #=> {"first"=>42}
With an array you use << to push a single element.
With a hash you are tracking not one element but two (both the key and value).
So for example:
my_key = "foo"
my_val = "bar"
my_hash = {}
my_hash[key] = val
Sure, you can do this in a loop.
I would recommend RubyMonk to learn more about this but their website is down. So I can recommend this gist which shows some examples or simply read the Hash section of any ruby tutorial.
Here are the two ways to add to a Hash
hash[str1] = "example string"
hash.merge!(str1 => "example string")
If you don't care about indexing on a key, as a Hash is intrinsically a key/value store, you probably want a Set:
require 'set'
set = Set.new
set << gets.chomp
A set is like a keyless hash, it's an un-ordered collection of things but with the side benefit that lookups for elements in the set are quick and they're also automatically uniqued, adding the same thing twice has no effect.
The alternative here is to put something in the Hash with the value as the key and any other value as a placeholder:
values = { }
values[input.gets] = true
This is like a Set but is probably less efficient to use if you don't care about values.
Ok, it isn't array so '<<' can't be work.
You should use this:
your_hash = {}
hash_key = "x"
hash_value = "y"
your_hash[:hash_key] = hash_value
It's all.

How to save an array of information coming from a hash in Ruby

I am new to ruby and don't have much experience with hashes, I have a variable named tweets and it is a hash as such:
{"statuses"=>[{"metadata"=>{"result_type"=>"recent", "iso_language_code"=>"tl"}, "lang"=>"tl"}]}
I would like to save the array of information as a separate variable in an array. How would I go about this?
Hash's have 2 very nice methods,
hash.values
hash.keys
in your case -
h = {"statuses"=>[{"metadata"=>{"result_type"=>"recent", "iso_language_code"=>"tl"}, "lang"=>"tl"}]}
p h.values
p.keys
These output arrays of each type. This might be what you want.
Also, this question will very well be closed. 1 Google search reported several Hash to Array SO questions.
Ruby Hash to array of values
Converting Ruby hashes to arrays
If you have a Hash like so:
hash = {:numbers => [1,2,3,4]}
And you need to capture the array into a new variable. You can just access the key and assign it to a new variable like so:
one_to_five = hash[:numbers]
However, note that the new variable actually holds the array that is in the hash. So altering the hash's array alters the new variable's array.
hash[:numbers] << 6
puts one_to_five #=> [1,2,3,4,5,6]
If you use dup, it will create a copy of the array so it will be two separate arrays.
one_to_five = hash[:numbers].dup
hash[:numbers] << 6
puts one_to_five #=> [1,2,3,4,5]
So, in your case:
hash = {'statuses' => [{"metadata"=>{"result_type"=>"recent", "iso_language_code"=>"tl"}, "lang"=>"tl"}]}
new_array = hash['statuses'].dup
However, it would be interesting to see what it is you are wishing to accomplish with your code, or at least get a little more context, because this may not be the best approach for your final goal. There are a great many things you can do with Arrays and Hashes (and Enumerable) and I would encourage you to read through the documentation on them.

ruby: search an multi-dimensional array for a value and update if needed

Trying to look through an array and see if a particular value is set and if it is, update the numbers attached to it.
Example:
test = [['test',1,2],['watch',1,2],['fish',1,2]]
So I'd like to search this array for 'test' - if it exists, amend the values '1,2', if it doesn't exist, just add the new search term into the array.
New to ruby and having trouble searching inside a multi-dimensional array and getting the key back
I'd go for the hash method suggested in the comments, but if you're really wanting to store your data in the multidimensional array like that I suppose you could do something like:
search_term = "test"
search_item= nil
test.each do |item|
if item.include? search_term
search_item = item
end
end
if search_item.nil?
test << [search_term]
else
search_item << [1,2]
end
I think that would do it (although I'm a little fuzzy on what you were wanting to do after you found the item).

Ruby arrays and non-incremental indexes

I have an array in ruby, and I am setting the index to id of object like below.
My first question is:
This code works:
#array = Array.new(#objects.size)
for i in 0...#objects.size
#array[i] = #objects[i].value
end
but when I do:
#array[#objects[i].id] = #objects[i].value
it says:
undefined method [] for nil::NilClass
I tried putting 100 or 1000 instead of i to make sure it's not about "index out of range", but those worked, I tried converting id to int by using to_i even though it should already be an int, but it still doesn't work. I don't get it.
My second question is:
If I get to make the ids work, does saying Array.new(#objects.size) become usless?
I am not using indexes 0 to size but IDs, so what is happening? Is it initializing indexes 0...size to nil or is it just creating a space for up to x objects?
EDIT:
So I've been told it is better to use Hash for this, and I agree, But I still seem to have the same error in the same situation (just changed Array.new(#objects.size)toHash.new)
Thats not how Arrays work in Ruby. You can however use a hash to do this, and look them up using the method you want:
#lookup_hash = Hash.new
for i in 0...#objects.size
#lookup_hash[#objects[i].id] = #objects[i].value
end
Now you can do:
#lookup_hash[#some_object.id]
And it will return that object's value as you have stored it.
Additional Info
You could also rewrite your loop like this, since you dont need the index anymore:
#lookup_hash = Hash.new
#objects.each do |obj|
#lookup_hash[obj.id] = obj.value
end
A little bit more readable in my opinion.
Your're trying to use an array like a hash. Try this:
Hash[#objects.map{|o| [o.id, o.value] }]
Take a look at the Array and Hash documentations.
#array = #objects.map { |obj| obj.value }
You can, but you don't need to specify the size when creating an array. Anyway, try to use the functional capabilities of Ruby (map, select, inject) instead of C-like imperative loops.
You could use map to do this in a rubyish way:
#array = #objects.map { |o| o.value }

Array from a custom class in 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.

Resources