Page 1 of 1

Ruby Help

Posted: Tue Mar 28, 2017 9:18 pm
by DaveyBoy
Hi all

Needing some help if one of you Ruby experts could assist.

I have a hash that I need to change:
Image

I've been Googling this for two days now to no avail, so I thought I'd ask here :D

In order to get the result I want I have to call a definition and change it, surely it must be possible to get the result in one definition... its self explanatory if you care to have a look:

Code: Select all

@my_hash = { 0 =>"Piano", 1 =>"Guitar", 5 =>"Flute" }

def my_1st_attempt   
   (0..6).map {|n| a = @my_hash.fetch(n,"- - -");Hash[n,a]}
end

def result_that_i_want
   my_1st_attempt.reduce Hash.new, :merge
end

watch "my_1st_attempt", my_1st_attempt

watch "result_that_i_want", result_that_i_want



Hope someone can help :cry:

PS sorry for the blurred pic . . . Had to resize it

Re: Ruby Help

Posted: Wed Mar 29, 2017 1:18 am
by KG_is_back
basically what you want to do is to add element to a hash if it doesn't already exist. There are several ways to do this:

Code: Select all

#version 1
(0..6).each{|n|
@my_hash[n] = @my_hash[n] || "- - -" #if fetched element is nil, puts "- - -" in its place
}

#version 2
(0..6).each{|n|
if not(@my_hash.has_key?(n)) #if given key is not present in hash
@my_hash[n] = "- - -" #put new element in that place
end

#version 3
#this version adds default element to the hash, which is returned by default unless specific value is specified
#this is different from your expected output, but it might be what you actually want.
@my_hash.default="- - -"
@my_hash[1] #returns "Guitar"
@my_hash[2] #returns "- - -" because key 2 is not present in the hash

}


Re: Ruby Help

Posted: Wed Mar 29, 2017 8:43 pm
by DaveyBoy
Hi KG

Thanks for the quick reply
Yep... that did the trick. I had to play about with it to get it to do what I want it to do but I got there in the end thanks to your help :D

Image

I am auto-generating blank lines in a list and this does the job perfectly.

Thanks again KG