simple-exercises/ruby-exercises/easy-10.rb
# Write a function that takes a string and
# returns a hash in which each key is a character in the string
# pointing to an array indicating the index that the character
# first occurs and last occurs.
#
# If the character occurs only once, the array should hold a single index
#
# Example:
#
# str = "banana"
# return {"b" => [0], "a" => [1, 5], "n" => [2, 4]}
# "b" occurs once at index 0
# "a" occurs three times, but the first is at index 1 and the last is at index 5
# "n" occurs three times, but the first is at index 2 and the last is at index 4
Write a function that takes a string and
returns a hash in which each key is a character in the string
pointing to an array indicating the index that the character
first occurs and last occurs.

If the character occurs only once, the array should hold a single index




Write a function that takes a string and returns a hash in which each key is a character in the string pointing to an array indicating the index that the character first occurs and last occurs . If the character occurs only once the array should hold a single index
def first_last_indices(str)
  indices = Hash.new()
  (0...str.length).each do |i|
    c = str[i]
    if !indices.include?(c)
      indices[c] = [i]
    end
  end
  n = str.length - 1
  n.downto(0) do |i|
    c = str[i]
    if indices[c].length == 2
      next
    end
    if indices[c][0] != i
      indices[c] << i
    end
  end
  indices
end
def first_last_indices ( str ) indices = Hash . new ( ) ( 0 ... str . length ) . each do | i | c = str [ i ] if ! indices . include? ( c ) indices [ c ] = [ i ] end end n = str . length - 1 n . downto ( 0 ) do | i | c = str [ i ] if indices [ c ] . length == 2 next end if indices [ c ] [ 0 ] != i indices [ c ] << i end end indices end
Write a function that takes a string and
returns a hash in which each key is a character in the string
pointing to an array indicating the index that the character
first occurs and last occurs.
Write a function that takes a string and returns a hash in which each key is a character in the string pointing to an array indicating the index that the character first occurs and last occurs .
str
<not_specific>