Skip to content

Commit 3afa6d0

Browse files
committed
ohms law implementation
1 parent 8bb781f commit 3afa6d0

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

DIRECTORY.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,9 @@
8787
* [Fibonacci](https://github.com/TheAlgorithms/Ruby/blob/master/dynamic_programming/fibonacci.rb)
8888
* [Pascal Triangle Ii](https://github.com/TheAlgorithms/Ruby/blob/master/dynamic_programming/pascal_triangle_ii.rb)
8989

90+
## Electronics
91+
* [Ohms Law](https://github.com/TheAlgorithms/Ruby/blob/master/electronics/ohms_law.rb)
92+
9093
## Maths
9194
* [3Nplus1](https://github.com/TheAlgorithms/Ruby/blob/master/maths/3nPlus1.rb)
9295
* [Abs](https://github.com/TheAlgorithms/Ruby/blob/master/maths/abs.rb)

electronics/ohms_law.rb

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# A ruby program for Ohms Law, which is used to calculate Voltage for the given Resistance and Current.
2+
# Ohms Law -> V = I * R
3+
# Reference: https://en.wikipedia.org/wiki/Ohm's_law
4+
5+
def ohms_law(i, r)
6+
if(i > 0 && r > 0)
7+
"The voltage for given #{i} ampheres current and #{r} ohms resistance is #{r * i} volts."
8+
else
9+
raise
10+
end
11+
rescue
12+
"Error: Please provide valid inputs only!"
13+
end
14+
15+
# Valid inputs
16+
puts(ohms_law(5, 10))
17+
# The voltage for given 5 ampheres current and 10 ohms resistance is 50 volts.
18+
puts(ohms_law(2.5, 6.9))
19+
# The voltage for given 2.5 ampheres current and 6.9 ohms resistance is 17.25 volts.
20+
puts(ohms_law(0.15, 0.84))
21+
# The voltage for given 0.15 ampheres current and 0.84 ohms resistance is 0.126 volts.
22+
23+
# Invalid inputs
24+
puts(ohms_law(5, -10))
25+
# Error: Please provide valid inputs only!
26+
puts(ohms_law(-5, -10))
27+
# Error: Please provide valid inputs only!
28+
puts(ohms_law(5, "10"))
29+
# Error: Please provide valid inputs only!
30+
puts(ohms_law("a", 10))
31+
# Error: Please provide valid inputs only!

0 commit comments

Comments
 (0)