Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is string.oct in Ruby?

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The oct method of a string in Ruby converts the leading number characters to their corresponding octal value. If there is no conversion, the method returns 0.

Syntax

str.oct

Parameters

  • str: The string whose leading number character(s) we want to convert to an octal value.

Return value

The oct method returns an octal value that is equivalent to the leading number character(s) of str. If there is no conversion, it returns 0.

Code example

# create strings
str1 = "1hello"
str2 = "345hellos"
str3 = "hello"
str4 = "-4hello"
# convert to octal
a = str1.oct
b = str2.oct
c = str3.oct
d = str4.oct
# print results
puts a
puts b
puts c
puts d
Convert Leading Number Characters to Octal Equivalent

Explanation

  • Lines 2 to 5: We create some strings. These are the strings whose leading number characters we want to convert to their corresponding octal values.

  • Lines 8 to 11: We call the oct method on each string we created. We then pass the results to variables a, b, c, and d.

  • Lines 14 to 17: We print the results.

The leading number characters are converted to their octal equivalents. Where there is no conversion, a 0 is returned.

RELATED TAGS

ruby
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring