Skip to content

Commit b56b033

Browse files
Add Linear Search in Ruby (#5170)
1 parent 93f79fd commit b56b033

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

archive/r/ruby/linear-search.rb

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
USAGE = 'Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")'
2+
3+
4+
if ARGV.length < 2
5+
puts USAGE
6+
return
7+
end
8+
9+
# the first input (list of numbers)
10+
list_input = ARGV[0]
11+
#second input (number to find)
12+
target_input = ARGV[1]
13+
14+
#check if the input is empty
15+
if list_input.strip.empty? || target_input.strip.empty?
16+
puts USAGE
17+
return
18+
end
19+
20+
begin
21+
#split list by the commas, trim the spaces, then turn into intgers
22+
numbers = list_input.split(',').map { |s| s.strip.to_i }
23+
24+
#convert second number to integer
25+
target = Integer(target_input)
26+
rescue ArgumentError
27+
# if conversion fails we show the usage message
28+
puts USAGE
29+
return
30+
end
31+
32+
#track if we find the number
33+
found = false
34+
35+
# go through each number in the list
36+
numbers.each do |n|
37+
if n == target
38+
found = true
39+
# stop searching once we find it
40+
break
41+
end
42+
end
43+
44+
# print result as true or false
45+
if found
46+
puts "true"
47+
else
48+
puts "false"
49+
end
50+
51+
52+
53+

0 commit comments

Comments
 (0)