Skip to content
Programming101
Programmingoneonone
  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programmingoneonone

HackerRank Ruby – Strings – Indexing problem solution

YASH PAL, 31 July 2024

In this HackerRank Ruby – Strings – Indexing problem solution In this challenge, your task is to code a serial_average method which is described below:

It takes a fixed-width string in the format: SSS-XX.XX-YY.YY. SSS is a three-digit serial number, XX.XX and YY.YY are two-digit numbers including up to two decimal digits.

It returns a string containing the answer in format SSS-ZZ.ZZ where SSS is the serial number of that input string, and ZZ.ZZ is the average of XX.XX and YY.YY.

All numbers are rounded off to two decimal places.

For example:

> serial_average(‘002-10.00-20.00’)

“002-15.00”

You can use string interpolation to insert Ruby code within a string.

For example:

> tmp = 123

> “Hello #{tmp}”

Hello 123

HackerRank Ruby - Strings - Indexing problem solution

Problem solution.

# Your code here
def serial_average(n)
    serial = n[0,3]
    first_num = n[4,5].to_f.round(2)
    sec_num = n[10,5].to_f.round(2)
    average = ((first_num + sec_num) / 2).round(2)
    
    return "#{serial}-#{average}"
end

Second solution.

# Your code here
def serial_average(s)
    serial = s[0, 3]
    x = s[4, 5].to_f
    y = s[10, 5].to_f
    z = (x + y) / 2
    "#{serial}-#{'%.2f' % z}"
end

Third solution.

def serial_average(s)
    sss = s[0..2]
    x_s = s[4..8].to_f
    y_s = s[10..14].to_f

    avg = ((x_s + y_s) / 2).round(2)
    return "#{sss}-#{avg}"
end

coding problems solutions Ruby Solutions

Post navigation

Previous post
Next post

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2025 Programmingoneonone | WordPress Theme by SuperbThemes