I am confused with this if statement?


#1

This is my syntax
a=2 // assign integer value
b=3 // assign integer value

if a == b // I believe (== means comparing string).
puts " I am getting right message"
else
puts " I am getting wrong message"
end
// provide me appropriate output
a=2
b=3

if a = b // comparing integers
puts " I am getting right message"
else
puts " I am getting wrong message"
end
// get the wrong output


#2

The short answer:

if a = b

should be

if a == b

The long answer, with examples:

= is used only for assigning values to variables.

#examples
my_num = 5
my_string = "hello"
my_boolean = true

== is used for comparisons of any objects, whether they be integers, strings, booleans, etc.

#comparing integers
a = 2
b = 3

puts a == b
# ==> false

#comparing strings
my_string = "hello"
your_string = "hello"

puts my_string == your_string
# ==> true

Also, since you're using Ruby, it's a good idea to get in the habit of using # for comments (and =begin and =end for multiline comments) rather than //.

I hope this helps! :slight_smile:


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.