define a function that takes a string like "m" and displays only the "size" for [{p: 10, n: "m", size: {s: 7, m: 2}}] in ruby

To define a function in Ruby that takes a string and displays the "size" value for a given object in an array, you can use the following code:

main.rb
def display_size(data, string)
  data.each do |obj|
    if obj[:"n"] == string
      puts obj[:"size"][:"s"]
    end
  end
end

data = [{p: 10, n: "m", size: {s: 7, m: 2}}]
display_size(data, "m")
197 chars
11 lines

This function display_size takes two parameters: data (the array of objects) and string (the string to match against the "n" key in the objects).

Within the function, we iterate over each object in the data array using each. We check if the "n" value of the current object matches the string parameter. If it does, we then access the "size" value and display the "s" value using puts.

In the example given, the result of calling display_size(data, "m") will output 7.

related categories

gistlibby LogSnag