diff options
| author | Mariano Spadaccini <spadacciniweb@gmail.com> | 2025-09-29 13:42:34 +0200 |
|---|---|---|
| committer | Mariano Spadaccini <spadacciniweb@gmail.com> | 2025-09-29 13:42:34 +0200 |
| commit | ac32c0a0e096ef0b3b2e706030d796108954400d (patch) | |
| tree | 1bd23bb631f5e144ce5b4de3ca30656f7d2c1009 | |
| parent | 48ac9bfec6c18250a4b47a33062e77528ca91b6c (diff) | |
| download | perlweeklychallenge-club-ac32c0a0e096ef0b3b2e706030d796108954400d.tar.gz perlweeklychallenge-club-ac32c0a0e096ef0b3b2e706030d796108954400d.tar.bz2 perlweeklychallenge-club-ac32c0a0e096ef0b3b2e706030d796108954400d.zip | |
Add ch-2 in Ruby
| -rw-r--r-- | challenge-341/spadacciniweb/ruby/ch-2.rb | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/challenge-341/spadacciniweb/ruby/ch-2.rb b/challenge-341/spadacciniweb/ruby/ch-2.rb new file mode 100644 index 0000000000..94ae6e1ffc --- /dev/null +++ b/challenge-341/spadacciniweb/ruby/ch-2.rb @@ -0,0 +1,63 @@ +# Task 2: Reverse Prefix +# Submitted by: Mohammad Sajid Anwar +# +# You are given a string, $str and a character in the given string, $char. +# Write a script to reverse the prefix upto the first occurrence of the given $char in the given string $str and return the new string. +# +# Example 1 +# Input: $str = "programming", $char = "g" +# Output: "gorpmming" +# +# Reverse of prefix "prog" is "gorp". +# +# Example 2 +# Input: $str = "hello", $char = "h" +# Output: "hello" +# +# Example 3 +# Input: $str = "abcdefghij", $char = "h" +# Output: "hgfedcbaj" +# +# Example 4 +# Input: $str = "reverse", $char = "s" +# Output: "srevere" +# +# Example 5 +# Input: $str = "perl", $char = "r" +# Output: "repl" + +def reverse_prefix(str, char) + chars = str.split('') + new_str = '' + (1..str.length).each do |_| + letter = chars.shift + new_str.concat(letter) + if letter == char + new_str = new_str.reverse + break + end + end + new_str.concat(chars.join()) + + printf "'%s' '%s' -> '%s'\n", str, char, new_str +end + +str = "programming" +char = "g" +reverse_prefix(str, char) + +str = "hello" +char = "h" +reverse_prefix(str, char) + +str = "abcdefghij" +char = "h" +reverse_prefix(str, char) + +str = "reverse" +char = "s" +reverse_prefix(str, char) + +str = "perl" +char = "r" +reverse_prefix(str, char) |
