for an input like: `%w[black brown white], write a function that takes the index of 1st element and index of 2nd element and combines them into a digit in ruby

In Ruby, you can use the join method to concatenate the elements of an array into a string. To combine the elements at the given indices into a single digit, you can do the following:

main.rb
def combine_elements(arr, index1, index2)
  digit = arr[index1] + arr[index2]
  digit.to_i
end

arr = %w[black brown white]
index1 = 0
index2 = 1

combined_digit = combine_elements(arr, index1, index2)
puts combined_digit
# Output: 7
234 chars
13 lines

In the above code, the function combine_elements takes the array arr, index1, and index2 as parameters. It then concatenates the elements at the given indices (arr[index1] and arr[index2]) and converts the resulting string to an integer using the to_i method. Finally, it returns the combined digit.

In the given example, arr contains %w[black brown white], and we are combining the elements at index 0 (black) and index 1 (brown). The combined digit is 7.

related categories

gistlibby LogSnag