Ruby: new array from one value in an array of objects - ruby

Forgive me if this has already been asked, I couldn't find it.
I have an array of objects, like:
[<#Folder id:1, name:'Foo', display_order: 1>,
<#Folder id:1, name:'Bar', display_order: 2>,
<#Folder id:1, name:'Baz', display_order: 3>]
I'd like to convert that array into an array just of the names, like:
['Foo','Bar','Baz']
and, while I'm at it it would be nice if I could use the same technique down the road to create an array from two of the parameters, ie name and display order would look like:
[['Foo',1],['Bar',2],['Baz',3]]
What's the best 'Ruby Way' to do this kind of thing?
Thanks!

How about these?
# ['Foo','Bar','Baz']
array = folders.map { |f| f.name }
# This does the same, but only works on Rails or Ruby 1.8.7 and above.
array = folders.map(&:name)
# [['Foo',1],['Bar',2],['Baz',3]]
array = folders.map { |f| [f.name, f.display_order] }

How about:
a.collect {|f| f.name}

You can do
array.map { |a| [a.name, a.display_order] }

To get ['Foo','Bar','Baz'] , you can do: array.map(&:name)
For the second one you could use array.map {|a| [a.id, a.name] }

Related

Hash Parsing with Ruby

I have the array of hash as shown below:
#line_statuses = [
{:name=>"1", :status=>"online"},
{:name=>"2", :status=>"online"}
]
I'd like to parse each hash inside of #line_statuses array so that I can print out the name and status as shown below.
1: online
2: online
How would I go about doing this?
Technically your #line_statuses variable is an array, so what you have is an array of hashes. In Ruby, to iterate over an array we use the .each method. Then, in each iteration, we can access the values of the hash using the defined keys:
#line_statuses.each do |hash|
puts hash[:name]
puts hash[:status]
end
So simple...:
#line_statuses.each do |line_status|
puts "#{line_status[:name]}: #{line_status[:status]}"
end
try #line_statuses.each{|i| puts i[:name],i[:status]}
Pretty simple:
#line_statuses.each { |line_status| puts "#{line_status[:name]}: #{line_status[:status]}" }

Find the tuple with the right ID ruby

Hi I have a list of tuples (arrays) and I want to find the tuple that matches an ID in the first object of the tuple. As an example here's what the data looks like
[[object1, stat1],[object2, stat2], etc]
What I want to do is detect an object ID and then grab the stat to go with it. What's the best way to do this?
You could do soemthing like this using ruby select: http://www.ruby-doc.org/core-2.1.1/Enumerable.html#method-i-select
a = [["object1", "stat1"],["object2", "stat2"]]
a.select { |elem| elem.include?("object1") }
I suggest you convert your array
arr = [["object1", "stat1"],["object2", "stat2"],["object3", "stat3"]]
to a hash:
hash = Hash[arr]
#=> {"object1"=>"stat1", "object2"=>"stat2", "object3"=>"stat3"}
or, for Ruby v2.0+
hash = arr.to_h
#=> {"object1"=>"stat1", "object2"=>"stat2", "object3"=>"stat3"}
so that you can retrieve values directly:
hash["object2"] #=> "stat2"
Find you say? Then how about using Enumerable#find?
a = [["object1", "stat1"],["object2", "stat2"],["object3", "stat3"]]
id = a[0][0].object_id
stat = a.find { |e| e[0].object_id == id }[1]

Ruby - If element in array contains a certain character, return the associated element(s)

Example:
my_array = ['2823BII','4A','76B','10J']
[using magical method delete_if_doesnt_contain()]
my_array.map! do |elements|
elements.delete_if_doesnt_contain('A')
end
I want that to set my_array = ['4A']
Even if I could iterate through an array and just return the index of the element that contains an 'A' I'd be happy. Thanks for any help!
Thanks for the answers below, but one more question.
other_array = ['4']
my_var = other_array.to_s
my_array.select!{|x| x.include?(my_var)}
This isn't working for me. What am I missing? Something happen when I converted the array to a string?
Very easy using #select :
my_array = ['2823BII','4A','76B','10J']
my_array.select { |str| str.include?('A') }
# => ["4A"]
Or if you want to modify the source array, do use the bang version of select :-
my_array.select! { |str| str.include?('A') }
Arup's answer is correct.
However, to answer your last question specifically, "iterate through an array and just return the index of the element that contains an 'A'", the "index" method returns the index for a matching element:
my_array.index {|x| x.include?('A') }
The grep method is a lot shorter
my_array = ['2823BII','4A','76B','10J']
my_array.grep /A/

how to name an object reference (handle) dynamically in ruby

So I have a class like this:
def Word
end
and im looping thru an array like this
array.each do |value|
end
And inside that loop I want to instantiate an object, with a handle of the var
value = Word.new
Im sure there is an easy way to do this - I just dont know what it is!
Thanks!
To assign things to a dynamic variable name, you need to use something like eval:
array.each do |value|
eval "#{value} = Word.new"
end
but check this is what you want - you should avoid using eval to solve things that really require different data structures, since it's hard to debug errors created with eval, and can easily cause undesired behaviour. For example, what you might really want is a hash of words and associated objects, for example
words = {}
array.each do |value|
words[value] = Word.new
end
which won't pollute your namespace with tons of Word objects.
Depending on the data structure you want to work with, you could also do this:
# will give you an array:
words = array.map { |value| Word.new(value) }
# will give you a hash (as in Peter's example)
words = array.inject({}) { |hash, value| hash.merge value => Word.new }
# same as above, but more efficient, using monkey-lib (gem install monkey-lib)
words = array.construct_hash { |value| [value, Word.new ] }

Ruby: How do I join elements of an array together with a prefix?

I have an array like so:
["marblecake", "also", "the", 1337]
I would like to get back a string which contains each element of the array prefixed by some specified string, then joined together by another specified string. For example,
["marblecake", "also", "the", 1337].join_with_prefix("%", "__")
should result in
# => %marblecake__%also__%the__%1337
How might I do this?
If your array is in a then this one-liner will do it
a.map { |k| "%#{k}" }.join("_")
You could easily put this in a function of your own - even add it to the Array class so that you can call it on an array, like in your example.
Note that the '!' version of map (map!) will modify the array in place - perhaps not your intent.
Although this is very old question, I'd like to add this:
a.any? && "%".+(a.join("__%"))
As per the above suggestion:
class Array
def join_with_prefix(prefix,separator)
self.collect {|e| prefix.to_s + e }.join(separator)
end
end
p ['ab','cd','ef'].join_with_prefix('%','__')
=> "%ab__%cd__%ef"
I was looking for a solution to this today.I found this question.This was my solution.
array = ["marblecake", "also", "the", 1337];
arrayString = ''
array.each{|x| arrayString += "%" + x + "__"}

Resources